@cfp-studio/core 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/index.d.mts +218 -0
- package/dist/index.d.ts +218 -0
- package/dist/index.mjs +1846 -0
- package/package.json +53 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1846 @@
|
|
|
1
|
+
import { decodePreviewableId } from '@cfp-studio/analyzer-api';
|
|
2
|
+
import { RPCs } from '@cfp-studio/api';
|
|
3
|
+
import { UNKNOWN_TYPE } from '@cfp-studio/type-analyzer';
|
|
4
|
+
import { createStackedReader, createFileSystemReader } from '@cfp-studio/vfs';
|
|
5
|
+
import express from 'express';
|
|
6
|
+
import cors from 'cors';
|
|
7
|
+
import fs$1 from 'fs-extra';
|
|
8
|
+
import { createHttpTerminator } from 'http-terminator';
|
|
9
|
+
import { createRequire } from 'node:module';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import pino from 'pino';
|
|
12
|
+
import PinoPretty from 'pino-pretty';
|
|
13
|
+
import { exclusivePromiseRunner } from 'exclusive-promises';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import url from 'node:url';
|
|
16
|
+
import { globby } from 'globby';
|
|
17
|
+
import net from 'node:net';
|
|
18
|
+
import { assertNever } from 'assert-never';
|
|
19
|
+
import axios from 'axios';
|
|
20
|
+
import viteTsconfigPaths from '@fwouts/vite-tsconfig-paths';
|
|
21
|
+
import { PREVIEW_CONFIG_NAMES, readConfig } from '@cfp-studio/config';
|
|
22
|
+
import fakeExportedTypesPlugin from 'rollup-plugin-friendly-type-imports';
|
|
23
|
+
import { loadTsconfig } from 'tsconfig-paths/lib/tsconfig-loader.js';
|
|
24
|
+
import * as vite from 'vite';
|
|
25
|
+
import { transformWithEsbuild, searchForWorkspaceRoot } from 'vite';
|
|
26
|
+
import { z } from 'zod';
|
|
27
|
+
import { escape } from 'html-escaper';
|
|
28
|
+
import { launchEditorMiddleware } from '@cfp-studio/middleware';
|
|
29
|
+
|
|
30
|
+
function getCacheDir(rootDir) {
|
|
31
|
+
try {
|
|
32
|
+
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
|
|
33
|
+
const { version } = JSON.parse(
|
|
34
|
+
// 同步读取 package.json 文件,使用 UTF-8 编码
|
|
35
|
+
fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8")
|
|
36
|
+
);
|
|
37
|
+
return path.resolve(rootDir, "node_modules", ".previewjs", `v${version}`);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
throw new Error(`\u65E0\u6CD5\u83B7\u53D6 @cfp-studio/core \u7684\u7248\u672C\u53F7.
|
|
40
|
+
${e}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function findFiles(rootDir, pattern, options = {}) {
|
|
45
|
+
const gitRootPath = await findGitRoot(rootDir);
|
|
46
|
+
const relativePath = path.relative(gitRootPath, rootDir);
|
|
47
|
+
const relativePrefix = relativePath ? relativePath + path.sep : "";
|
|
48
|
+
const files = await globby(relativePrefix + pattern, {
|
|
49
|
+
gitignore: true,
|
|
50
|
+
ignore: ["**/node_modules/**"],
|
|
51
|
+
cwd: gitRootPath,
|
|
52
|
+
absolute: true,
|
|
53
|
+
followSymbolicLinks: false,
|
|
54
|
+
suppressErrors: true,
|
|
55
|
+
deep: options.maxDepth
|
|
56
|
+
});
|
|
57
|
+
let normalizedRootDirPath = rootDir.replace(/\\/g, "/");
|
|
58
|
+
if (!normalizedRootDirPath.endsWith("/")) {
|
|
59
|
+
normalizedRootDirPath += "/";
|
|
60
|
+
}
|
|
61
|
+
return files.filter((f) => f.startsWith(normalizedRootDirPath)).sort();
|
|
62
|
+
}
|
|
63
|
+
async function findGitRoot(dirPath, fallback = dirPath) {
|
|
64
|
+
try {
|
|
65
|
+
if (await fs$1.exists(path.join(dirPath, ".git"))) {
|
|
66
|
+
return dirPath;
|
|
67
|
+
}
|
|
68
|
+
const parentDirPath = path.dirname(dirPath);
|
|
69
|
+
if (!parentDirPath || parentDirPath === dirPath) {
|
|
70
|
+
return fallback;
|
|
71
|
+
}
|
|
72
|
+
return findGitRoot(parentDirPath, fallback);
|
|
73
|
+
} catch {
|
|
74
|
+
return fallback;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const FILES_REQUIRING_REDETECTION = /* @__PURE__ */ new Set([
|
|
79
|
+
"jsconfig.json",
|
|
80
|
+
"tsconfig.json",
|
|
81
|
+
"package.json",
|
|
82
|
+
"package-lock.json",
|
|
83
|
+
"pnpm-lock.yaml",
|
|
84
|
+
"yarn.lock"
|
|
85
|
+
]);
|
|
86
|
+
const oneAtATime = exclusivePromiseRunner();
|
|
87
|
+
function crawlFiles(logger, workspace, frameworkPlugin, options = {}) {
|
|
88
|
+
return oneAtATime(async () => {
|
|
89
|
+
logger.debug(
|
|
90
|
+
`\u5F00\u59CB\u626B\u63CF\u7EC4\u4EF6\uFF0C\u626B\u63CF\u53C2\u6570: ${JSON.stringify(options)}`
|
|
91
|
+
);
|
|
92
|
+
const detectionStartTimestamp = Date.now();
|
|
93
|
+
const cacheFilePath = path.join(
|
|
94
|
+
getCacheDir(workspace.rootDir),
|
|
95
|
+
"components.json"
|
|
96
|
+
);
|
|
97
|
+
const absoluteFilePaths = await (async () => {
|
|
98
|
+
if (options.filePaths) {
|
|
99
|
+
return options.filePaths.map(
|
|
100
|
+
(filePath) => path.join(workspace.rootDir, filePath)
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
logger.debug(`\u626B\u63CF\u76EE\u5F55: ${workspace.rootDir}\uFF0C\u91C7\u96C6\u53EF\u626B\u63CF\u6587\u4EF6`);
|
|
104
|
+
const filePaths = await findFiles(
|
|
105
|
+
workspace.rootDir,
|
|
106
|
+
"**/*.@(js|jsx|ts|tsx|svelte|vue)"
|
|
107
|
+
);
|
|
108
|
+
logger.debug(`\u627E\u5230 ${filePaths.length} \u4E2A\u5305\u542B\u7EC4\u4EF6\u7684\u6587\u4EF6`);
|
|
109
|
+
return filePaths;
|
|
110
|
+
})();
|
|
111
|
+
const filePathsSet = new Set(
|
|
112
|
+
absoluteFilePaths.map(
|
|
113
|
+
(absoluteFilePath) => path.relative(workspace.rootDir, absoluteFilePath).replace(/\\/g, "/")
|
|
114
|
+
)
|
|
115
|
+
);
|
|
116
|
+
let existingCache = {
|
|
117
|
+
detectionStartTimestamp: 0,
|
|
118
|
+
components: [],
|
|
119
|
+
stories: []
|
|
120
|
+
};
|
|
121
|
+
if (fs$1.existsSync(cacheFilePath)) {
|
|
122
|
+
try {
|
|
123
|
+
existingCache = JSON.parse(
|
|
124
|
+
fs$1.readFileSync(cacheFilePath, "utf8")
|
|
125
|
+
);
|
|
126
|
+
} catch {
|
|
127
|
+
logger.warn(`\u65E0\u6CD5\u8F6C\u6362 ${cacheFilePath} \u4E2D\u5B58\u50A8\u7684\u7F13\u5B58\u4FE1\u606F`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (existingCache.detectionStartTimestamp < await detectionMinimalTimestamp(workspace.rootDir)) {
|
|
131
|
+
existingCache = {
|
|
132
|
+
detectionStartTimestamp: 0,
|
|
133
|
+
components: [],
|
|
134
|
+
stories: []
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const changedAbsoluteFilePaths = absoluteFilePaths.filter(
|
|
138
|
+
(absoluteFilePath) => {
|
|
139
|
+
const entry = workspace.reader.readSync(absoluteFilePath);
|
|
140
|
+
return entry?.kind === "file" && (options.forceRefresh || entry.lastModifiedMillis() >= existingCache.detectionStartTimestamp);
|
|
141
|
+
}
|
|
142
|
+
);
|
|
143
|
+
const refreshedFilePaths = new Set(
|
|
144
|
+
changedAbsoluteFilePaths.map(
|
|
145
|
+
(absoluteFilePath) => path.relative(workspace.rootDir, absoluteFilePath).replace(/\\/g, "/")
|
|
146
|
+
)
|
|
147
|
+
);
|
|
148
|
+
const shouldRecycle = ({ id }) => {
|
|
149
|
+
const filePath = decodePreviewableId(id).filePath;
|
|
150
|
+
return filePathsSet.has(filePath) && !refreshedFilePaths.has(filePath);
|
|
151
|
+
};
|
|
152
|
+
const recycledComponents = existingCache.components.filter(shouldRecycle);
|
|
153
|
+
const recycledStories = existingCache.stories.filter(shouldRecycle);
|
|
154
|
+
const { components: refreshedComponents, stories: refreshedStories } = await analyzeCore(
|
|
155
|
+
logger,
|
|
156
|
+
workspace,
|
|
157
|
+
frameworkPlugin,
|
|
158
|
+
changedAbsoluteFilePaths
|
|
159
|
+
);
|
|
160
|
+
const components = [...recycledComponents, ...refreshedComponents];
|
|
161
|
+
const stories = [...recycledStories, ...refreshedStories];
|
|
162
|
+
if (!options.filePaths) {
|
|
163
|
+
await fs$1.mkdirp(path.dirname(cacheFilePath));
|
|
164
|
+
const updatedCache = {
|
|
165
|
+
detectionStartTimestamp,
|
|
166
|
+
components,
|
|
167
|
+
stories
|
|
168
|
+
};
|
|
169
|
+
await fs$1.writeFile(cacheFilePath, JSON.stringify(updatedCache));
|
|
170
|
+
}
|
|
171
|
+
return { components, stories };
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
async function analyzeCore(logger, workspace, frameworkPlugin, changedAbsoluteFilePaths) {
|
|
175
|
+
const components = [];
|
|
176
|
+
const stories = [];
|
|
177
|
+
if (changedAbsoluteFilePaths.length === 0) {
|
|
178
|
+
return { components, stories };
|
|
179
|
+
}
|
|
180
|
+
logger.debug(
|
|
181
|
+
`\u5728\u4E0B\u8FF0\u6587\u4EF6\u4E2D\u67E5\u627E\u7EC4\u4EF6:
|
|
182
|
+
- ${changedAbsoluteFilePaths.map(
|
|
183
|
+
(absoluteFilePath) => path.relative(workspace.rootDir, absoluteFilePath)
|
|
184
|
+
).join("\n- ")}`
|
|
185
|
+
);
|
|
186
|
+
const found = await frameworkPlugin.crawlFiles(changedAbsoluteFilePaths);
|
|
187
|
+
logger.debug("\u7EC4\u4EF6\u68C0\u6D4B\u5B8C\u6210");
|
|
188
|
+
for (const component of found.components) {
|
|
189
|
+
components.push({
|
|
190
|
+
id: component.id,
|
|
191
|
+
sourcePosition: component.sourcePosition,
|
|
192
|
+
exported: component.exported
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
for (const story of found.stories) {
|
|
196
|
+
stories.push({
|
|
197
|
+
id: story.id,
|
|
198
|
+
sourcePosition: story.sourcePosition,
|
|
199
|
+
associatedComponentId: story.associatedComponent?.id || null
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return { components, stories };
|
|
203
|
+
}
|
|
204
|
+
async function detectionMinimalTimestamp(rootDir) {
|
|
205
|
+
const nodeModulesPath = path.join(rootDir, "node_modules");
|
|
206
|
+
let lastModifiedMillis = 0;
|
|
207
|
+
if (await fs$1.pathExists(nodeModulesPath)) {
|
|
208
|
+
for (const subdirectory of await fs$1.readdir(nodeModulesPath)) {
|
|
209
|
+
const subdirectoryPath = path.join(nodeModulesPath, subdirectory);
|
|
210
|
+
const stat = await fs$1.lstat(subdirectoryPath);
|
|
211
|
+
if (stat.isDirectory() || stat.isSymbolicLink()) {
|
|
212
|
+
lastModifiedMillis = Math.max(lastModifiedMillis, stat.mtimeMs);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
for (const f of FILES_REQUIRING_REDETECTION) {
|
|
217
|
+
const filePath = path.join(rootDir, f);
|
|
218
|
+
if (await fs$1.pathExists(filePath)) {
|
|
219
|
+
const stat = await fs$1.stat(filePath);
|
|
220
|
+
lastModifiedMillis = Math.max(lastModifiedMillis, stat.mtimeMs);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return lastModifiedMillis;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function getFreePort(min) {
|
|
227
|
+
for (let port = min; ; port++) {
|
|
228
|
+
if (await isAvailable(port)) {
|
|
229
|
+
return port;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async function isAvailable(port) {
|
|
234
|
+
return new Promise((resolve) => {
|
|
235
|
+
const server = net.createServer();
|
|
236
|
+
server.unref();
|
|
237
|
+
server.on("error", () => resolve(false));
|
|
238
|
+
server.listen(port, () => {
|
|
239
|
+
server.close(() => {
|
|
240
|
+
resolve(true);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const require$1 = createRequire(import.meta.url);
|
|
247
|
+
async function extractPackageDependencies(logger, rootDir) {
|
|
248
|
+
const packageJsonPath = path.join(rootDir, "package.json");
|
|
249
|
+
if (!await fs$1.pathExists(packageJsonPath)) {
|
|
250
|
+
return {};
|
|
251
|
+
}
|
|
252
|
+
const { dependencies, devDependencies, peerDependencies } = JSON.parse(
|
|
253
|
+
await fs$1.readFile(packageJsonPath, "utf8")
|
|
254
|
+
);
|
|
255
|
+
const allDependencies = {
|
|
256
|
+
...dependencies,
|
|
257
|
+
...devDependencies,
|
|
258
|
+
...peerDependencies
|
|
259
|
+
};
|
|
260
|
+
const dependenciesMap = /* @__PURE__ */ new Map();
|
|
261
|
+
for (const [name, version] of Object.entries(allDependencies)) {
|
|
262
|
+
let majorVersion = 0;
|
|
263
|
+
if (typeof version === "string") {
|
|
264
|
+
if (version.startsWith("^") || version.startsWith("~")) {
|
|
265
|
+
majorVersion = Number.parseInt(version.slice(1));
|
|
266
|
+
} else {
|
|
267
|
+
majorVersion = Number.parseInt(version);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const readInstalledVersion = async () => {
|
|
271
|
+
try {
|
|
272
|
+
const moduleEntryPath = findModuleEntryPath(name, rootDir);
|
|
273
|
+
let packagePath = moduleEntryPath;
|
|
274
|
+
while (packagePath !== path.dirname(packagePath)) {
|
|
275
|
+
const candidatePackageJsonPath = path.join(
|
|
276
|
+
packagePath,
|
|
277
|
+
"package.json"
|
|
278
|
+
);
|
|
279
|
+
if (fs$1.existsSync(candidatePackageJsonPath)) {
|
|
280
|
+
const packageInfo = JSON.parse(
|
|
281
|
+
await fs$1.readFile(candidatePackageJsonPath, "utf8")
|
|
282
|
+
);
|
|
283
|
+
if (typeof packageInfo.version === "string") {
|
|
284
|
+
return packageInfo.version;
|
|
285
|
+
}
|
|
286
|
+
throw new Error(`\u5305: ${candidatePackageJsonPath} \u7684\u7248\u672C\u53F7\u5F02\u5E38`);
|
|
287
|
+
}
|
|
288
|
+
packagePath = path.dirname(packagePath);
|
|
289
|
+
}
|
|
290
|
+
throw new Error(
|
|
291
|
+
`\u6839\u636E\u6A21\u5757: ${moduleEntryPath} \u7684\u5165\u53E3\u8DEF\u5F84\u65E0\u6CD5\u627E\u5230 package.json`
|
|
292
|
+
);
|
|
293
|
+
} catch (e) {
|
|
294
|
+
logger.error(
|
|
295
|
+
`\u65E0\u6CD5\u8BFB\u53D6\u5305: ${name} \u7684\u5B89\u88C5\u7248\u672C, \u4F60\u53EF\u80FD\u6CA1\u6709\u6B63\u786E\u5B89\u88C5\u9879\u76EE\u7684\u4F9D\u8D56\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u3002`,
|
|
296
|
+
e
|
|
297
|
+
);
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
dependenciesMap.set(name, { majorVersion, readInstalledVersion });
|
|
302
|
+
}
|
|
303
|
+
return Object.fromEntries(dependenciesMap);
|
|
304
|
+
}
|
|
305
|
+
function findModuleEntryPath(name, rootDir) {
|
|
306
|
+
try {
|
|
307
|
+
return require$1.resolve(name, {
|
|
308
|
+
paths: [rootDir]
|
|
309
|
+
});
|
|
310
|
+
} catch (e) {
|
|
311
|
+
if (e instanceof Error) {
|
|
312
|
+
if ("code" in e && e.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") {
|
|
313
|
+
const potentialMatch = e.message.match(
|
|
314
|
+
/No "exports" main defined in (.*)(\/|\\)package\.json/
|
|
315
|
+
);
|
|
316
|
+
if (potentialMatch) {
|
|
317
|
+
return potentialMatch[1] ?? "";
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
throw e;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function generateHtmlError(message) {
|
|
326
|
+
let _msg = message;
|
|
327
|
+
if (_msg.startsWith("Error: Build failed with 1 error:\n")) {
|
|
328
|
+
_msg = _msg.substring(message.indexOf("\n") + 1);
|
|
329
|
+
}
|
|
330
|
+
if (_msg.startsWith("Error:")) {
|
|
331
|
+
_msg = _msg.substring(_msg.indexOf(":") + 1);
|
|
332
|
+
}
|
|
333
|
+
_msg = _msg.trim();
|
|
334
|
+
return `<html>
|
|
335
|
+
<head>
|
|
336
|
+
<meta http-equiv="refresh" content="3">
|
|
337
|
+
<style>
|
|
338
|
+
body {
|
|
339
|
+
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
|
340
|
+
monospace;
|
|
341
|
+
white-space: pre-wrap;
|
|
342
|
+
background: #FCA5A5;
|
|
343
|
+
color: #7F1D1D;
|
|
344
|
+
margin: 8px;
|
|
345
|
+
font-size: 12px;
|
|
346
|
+
line-height: 1.5em;
|
|
347
|
+
}
|
|
348
|
+
</style>
|
|
349
|
+
<script>
|
|
350
|
+
// \u6CE8\u610F: \u8981\u4E0E iframe/preview/index.html \u4E2D\u7684\u4EE3\u7801\u4FDD\u6301\u540C\u6B65
|
|
351
|
+
const sendPreviewEvent = event => (
|
|
352
|
+
window.__PREVIEWJS_CONTROLLER__ || window.parent.__PREVIEWJS_CONTROLLER__
|
|
353
|
+
).onPreviewEvent(event);
|
|
354
|
+
sendPreviewEvent({
|
|
355
|
+
kind: "bootstrapping",
|
|
356
|
+
});
|
|
357
|
+
sendPreviewEvent({
|
|
358
|
+
kind: "error",
|
|
359
|
+
source: "load",
|
|
360
|
+
message: ${JSON.stringify(message)}
|
|
361
|
+
});
|
|
362
|
+
<\/script>
|
|
363
|
+
</head>
|
|
364
|
+
<body>${escape(message)}</body>
|
|
365
|
+
</html>`;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const extensions = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx"]);
|
|
369
|
+
const importRegexp = /import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;
|
|
370
|
+
function cssModulesWithoutSuffixPlugin() {
|
|
371
|
+
return {
|
|
372
|
+
name: "previewjs:css-modules-without-suffix",
|
|
373
|
+
/**
|
|
374
|
+
* 转换代码,为不带有 .module.css 后缀的 CSS 模块导入添加后缀
|
|
375
|
+
*
|
|
376
|
+
* @param code - 要转换的代码
|
|
377
|
+
* @param id - 模块的唯一标识符
|
|
378
|
+
* @returns 转换后的代码,如果不需要转换则返回 undefined
|
|
379
|
+
*/
|
|
380
|
+
async transform(code, id) {
|
|
381
|
+
const parts = id.split("?");
|
|
382
|
+
const _id = parts[0];
|
|
383
|
+
if (!_id) {
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (!extensions.has(path.extname(_id))) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
return code.replace(
|
|
390
|
+
importRegexp,
|
|
391
|
+
'import $1 from "$3.$4?$5&.module.css"'
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function invalidateStoriesModulesOnUpdate() {
|
|
398
|
+
return {
|
|
399
|
+
name: "previewjs:invalidate-stories-modules-on-update",
|
|
400
|
+
enforce: "post",
|
|
401
|
+
/**
|
|
402
|
+
* 转换函数,处理代码字符串。
|
|
403
|
+
* @param code - 输入的代码字符串。
|
|
404
|
+
* @returns 如果代码不包含 `import.meta.hot.accept`,则返回 null;否则返回修改后的代码。
|
|
405
|
+
*/
|
|
406
|
+
transform: (code) => {
|
|
407
|
+
if (!code.includes("import.meta.hot.accept(")) {
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
return `${code}
|
|
411
|
+
if (import.meta?.hot) {
|
|
412
|
+
import.meta.hot.accept(newModule => {
|
|
413
|
+
if (newModule?.default?.component) {
|
|
414
|
+
import.meta.hot.invalidate();
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
`;
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function localEval() {
|
|
424
|
+
return {
|
|
425
|
+
name: "previewjs:local-eval",
|
|
426
|
+
enforce: "post",
|
|
427
|
+
/**
|
|
428
|
+
* 转换代码的钩子函数
|
|
429
|
+
* @param code - 输入的代码字符串
|
|
430
|
+
* @param id - 文件的唯一标识符
|
|
431
|
+
* @returns 如果文件在 node_modules 目录中或包含查询参数,则返回 null;否则返回原始代码加上 PreviewJsEval 函数的代码
|
|
432
|
+
*/
|
|
433
|
+
transform: (code, id) => {
|
|
434
|
+
if (id.indexOf("/node_modules/") !== -1) {
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
if (id.indexOf("?") !== -1) {
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
return (
|
|
441
|
+
// 注意:这是一个大写命名的函数,这样它“看起来像”一个 React 组件。
|
|
442
|
+
// 这是为了防止破坏 React Refresh 功能,因为 React Refresh 期望所有导出的都是 React 组件。
|
|
443
|
+
`${code}
|
|
444
|
+
export const PreviewJsEval = (code, args = {}) => {
|
|
445
|
+
return eval("(({ " + Object.keys(args).join(", ") + "}) => { " + code + " })(args)");
|
|
446
|
+
}
|
|
447
|
+
`
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const PATH_PREFIX = "/__previewjs_internal__/preview.js?p=";
|
|
454
|
+
function previewScriptPlugin() {
|
|
455
|
+
return {
|
|
456
|
+
name: "previewjs:preview-script",
|
|
457
|
+
/**
|
|
458
|
+
* 加载钩子,当 Vite 尝试加载模块时调用
|
|
459
|
+
* @param {string} id - 要加载的模块的 ID
|
|
460
|
+
* @returns {string | void} - 如果匹配到预览脚本路径,则返回预览脚本的源代码;否则返回 undefined
|
|
461
|
+
*/
|
|
462
|
+
load(id) {
|
|
463
|
+
if (!id.startsWith(PATH_PREFIX)) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const base64EncodedOptions = id.substring(PATH_PREFIX.length);
|
|
467
|
+
const options = JSON.parse(
|
|
468
|
+
Buffer.from(base64EncodedOptions, "base64url").toString("utf8")
|
|
469
|
+
);
|
|
470
|
+
return previewScriptSource(options);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
function previewScriptSource({
|
|
475
|
+
previewablePath,
|
|
476
|
+
previewableName,
|
|
477
|
+
wrapperPath,
|
|
478
|
+
wrapperName,
|
|
479
|
+
detectedGlobalCssFilePaths
|
|
480
|
+
}) {
|
|
481
|
+
return `
|
|
482
|
+
// \u5BFC\u5165\u521D\u59CB\u5316\u76D1\u542C\u5668\u548C\u9884\u89C8\u7684\u51FD\u6570
|
|
483
|
+
import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";
|
|
484
|
+
// \u521D\u59CB\u5316\u76D1\u542C\u5668
|
|
485
|
+
initListeners();
|
|
486
|
+
// \u542F\u7528\u70ED\u66F4\u65B0
|
|
487
|
+
import.meta.hot.accept();
|
|
488
|
+
// \u521D\u59CB\u5316\u5237\u65B0\u51FD\u6570
|
|
489
|
+
let refresh = () => {};
|
|
490
|
+
// \u4E3A\u7A97\u53E3\u7684 __PREVIEWJS_IFRAME__ \u5BF9\u8C61\u6DFB\u52A0\u5237\u65B0\u65B9\u6CD5
|
|
491
|
+
window.__PREVIEWJS_IFRAME__.refresh = (options) => {
|
|
492
|
+
refresh(options);
|
|
493
|
+
if (options.refetchPreviewableModule) {
|
|
494
|
+
loadFreshPreviewableModule().then(previewableModule => refresh({
|
|
495
|
+
...options,
|
|
496
|
+
previewableModule,
|
|
497
|
+
}));
|
|
498
|
+
}
|
|
499
|
+
if (options.refetchWrapperModule) {
|
|
500
|
+
loadFreshWrapperModule().then(wrapperModule => refresh({
|
|
501
|
+
...options,
|
|
502
|
+
wrapperModule,
|
|
503
|
+
}));
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
// \u76D1\u542C\u53EF\u9884\u89C8\u6A21\u5757\u7684\u70ED\u66F4\u65B0
|
|
507
|
+
import.meta.hot.accept(["/${previewablePath}"], ([previewableModule]) => {
|
|
508
|
+
if (previewableModule) {
|
|
509
|
+
refresh({
|
|
510
|
+
previewableModule,
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
${wrapperPath ? `
|
|
516
|
+
const wrapperModulePromise = import(/* @vite-ignore */ "/${wrapperPath}?t=" + Date.now());
|
|
517
|
+
// \u76D1\u542C\u5305\u88C5\u5668\u6A21\u5757\u7684\u70ED\u66F4\u65B0
|
|
518
|
+
import.meta.hot.accept(["/${wrapperPath}"], ([wrapperModule]) => {
|
|
519
|
+
if (wrapperModule) {
|
|
520
|
+
// \u8C03\u7528\u5237\u65B0\u51FD\u6570\u66F4\u65B0\u9884\u89C8
|
|
521
|
+
refresh({
|
|
522
|
+
wrapperModule,
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
` : `
|
|
527
|
+
const wrapperModulePromise = Promise.all([${detectedGlobalCssFilePaths.map(
|
|
528
|
+
(cssFilePath) => `import(/* @vite-ignore */ "/${cssFilePath.replace(
|
|
529
|
+
/\\/g,
|
|
530
|
+
"/"
|
|
531
|
+
)}").catch(() => null)`
|
|
532
|
+
).join(",")}]).then(() => null);
|
|
533
|
+
`}
|
|
534
|
+
|
|
535
|
+
// Important: the wrapper must be loaded first as it may monkey-patch
|
|
536
|
+
// modules imported by the component module.
|
|
537
|
+
wrapperModulePromise.then(wrapperModule => {
|
|
538
|
+
// \u52A0\u8F7D\u65B0\u7684\u53EF\u9884\u89C8\u6A21\u5757
|
|
539
|
+
loadFreshPreviewableModule().then(previewableModule => {
|
|
540
|
+
// \u521D\u59CB\u5316\u9884\u89C8\u5E76\u66F4\u65B0\u5237\u65B0\u51FD\u6570
|
|
541
|
+
refresh = initPreview({
|
|
542
|
+
previewableModule,
|
|
543
|
+
previewableName: ${JSON.stringify(previewableName)},
|
|
544
|
+
wrapperModule,
|
|
545
|
+
wrapperName: ${JSON.stringify(wrapperName)},
|
|
546
|
+
});
|
|
547
|
+
});
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* \u52A0\u8F7D\u65B0\u7684\u53EF\u9884\u89C8\u6A21\u5757
|
|
552
|
+
* @returns {Promise<any>} - \u8FD4\u56DE\u4E00\u4E2A Promise\uFF0C\u89E3\u6790\u4E3A\u52A0\u8F7D\u7684\u53EF\u9884\u89C8\u6A21\u5757
|
|
553
|
+
*/
|
|
554
|
+
function loadFreshPreviewableModule() {
|
|
555
|
+
return import(/* @vite-ignore */ "/${previewablePath}?t=" + Date.now());
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* \u52A0\u8F7D\u65B0\u7684wrapper\u6A21\u5757
|
|
560
|
+
* @returns {Promise<any>} - \u8FD4\u56DE\u4E00\u4E2A Promise\uFF0C\u89E3\u6790\u4E3A\u52A0\u8F7D\u7684wrapper\u6A21\u5757
|
|
561
|
+
*/
|
|
562
|
+
function loadFreshWrapperModule() {
|
|
563
|
+
return import(/* @vite-ignore */ "/${wrapperPath}?t=" + Date.now());
|
|
564
|
+
}
|
|
565
|
+
`;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function publicAssetImportPluginPlugin({
|
|
569
|
+
rootDir,
|
|
570
|
+
publicDir
|
|
571
|
+
}) {
|
|
572
|
+
return {
|
|
573
|
+
name: "previewjs:public-asset-import",
|
|
574
|
+
/**
|
|
575
|
+
* 解析模块导入路径的钩子函数。
|
|
576
|
+
*
|
|
577
|
+
* @param source - 导入的源路径
|
|
578
|
+
* @param importer - 导入该模块的文件路径
|
|
579
|
+
* @returns 如果解析成功,返回解析后的路径;否则返回 undefined
|
|
580
|
+
*/
|
|
581
|
+
resolveId: async (source, importer) => {
|
|
582
|
+
if (!importer || !source.startsWith("/") || source.startsWith("/__previewjs__/")) {
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
const publicDirAbsolutePath = path.join(rootDir, publicDir);
|
|
586
|
+
const potentialPublicFilePath = path.join(publicDirAbsolutePath, source);
|
|
587
|
+
if (!potentialPublicFilePath.startsWith(publicDirAbsolutePath + path.sep)) {
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (!await fs$1.pathExists(potentialPublicFilePath)) {
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
return source;
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function toVitePath(absoluteFilePath) {
|
|
599
|
+
let _absoluteFilePath = absoluteFilePath;
|
|
600
|
+
if (_absoluteFilePath.match(/^[a-z]:/)) {
|
|
601
|
+
_absoluteFilePath = _absoluteFilePath[0]?.toUpperCase() + absoluteFilePath.substring(1);
|
|
602
|
+
}
|
|
603
|
+
return _absoluteFilePath.replace(/\\/g, "/");
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
const VIRTUAL_PREFIX = "/@cfp-studio-virtual:";
|
|
607
|
+
const VIRTUAL_PREFIX2 = "/@id/__x00__";
|
|
608
|
+
const jsExtensions = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx"]);
|
|
609
|
+
function maybeVirtual(originalId) {
|
|
610
|
+
let id = originalId;
|
|
611
|
+
if (id.startsWith(VIRTUAL_PREFIX)) {
|
|
612
|
+
id = id.slice(VIRTUAL_PREFIX.length);
|
|
613
|
+
}
|
|
614
|
+
if (id.startsWith("\0")) {
|
|
615
|
+
id = id.slice(1);
|
|
616
|
+
}
|
|
617
|
+
if (id.startsWith(VIRTUAL_PREFIX2)) {
|
|
618
|
+
id = id.slice(VIRTUAL_PREFIX2.length);
|
|
619
|
+
}
|
|
620
|
+
return [id, id !== originalId];
|
|
621
|
+
}
|
|
622
|
+
function virtualPlugin(options) {
|
|
623
|
+
const { reader, rootDir } = options;
|
|
624
|
+
return {
|
|
625
|
+
name: "previewjs:virtual-fs",
|
|
626
|
+
/**
|
|
627
|
+
* 解析模块ID。
|
|
628
|
+
* 处理虚拟文件的ID解析,判断是否需要将文件视为虚拟文件。
|
|
629
|
+
* @param originalId - 原始的模块ID。
|
|
630
|
+
* @param originalImporter - 原始的导入者ID。
|
|
631
|
+
* @returns 解析后的模块ID,如果不需要处理则返回null。
|
|
632
|
+
*/
|
|
633
|
+
resolveId: async (originalId, originalImporter) => {
|
|
634
|
+
const [importer, virtualImporter] = originalImporter ? maybeVirtual(originalImporter) : [null, false];
|
|
635
|
+
if (originalId.indexOf("/node_modules/") !== -1) {
|
|
636
|
+
return null;
|
|
637
|
+
}
|
|
638
|
+
let [id] = maybeVirtual(originalId);
|
|
639
|
+
id = id.split("?", 2)[0] ?? "";
|
|
640
|
+
const extension = path.extname(id);
|
|
641
|
+
let absoluteId;
|
|
642
|
+
if (path.isAbsolute(id)) {
|
|
643
|
+
absoluteId = id;
|
|
644
|
+
} else {
|
|
645
|
+
if (!importer) {
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
if (extension && !jsExtensions.has(extension) && extension !== ".svg") {
|
|
649
|
+
return path.join(path.dirname(importer), id);
|
|
650
|
+
}
|
|
651
|
+
absoluteId = path.join(path.dirname(importer), id);
|
|
652
|
+
}
|
|
653
|
+
const resolved = await resolveAbsoluteModuleId(absoluteId);
|
|
654
|
+
if (resolved) {
|
|
655
|
+
const [absoluteFilePath] = resolved;
|
|
656
|
+
if (await fs$1.pathExists(absoluteFilePath) && !virtualImporter) {
|
|
657
|
+
return null;
|
|
658
|
+
}
|
|
659
|
+
if (!absoluteId.endsWith(extension)) {
|
|
660
|
+
absoluteId += extension;
|
|
661
|
+
}
|
|
662
|
+
const resolvedId = VIRTUAL_PREFIX + absoluteFilePath.replace(/\\/g, "/");
|
|
663
|
+
return resolvedId;
|
|
664
|
+
}
|
|
665
|
+
return null;
|
|
666
|
+
},
|
|
667
|
+
/**
|
|
668
|
+
* 加载模块内容。
|
|
669
|
+
* 处理虚拟文件的内容加载,确保只加载允许访问的文件。
|
|
670
|
+
* @param id - 模块ID。
|
|
671
|
+
* @returns 模块的内容,如果不需要处理则返回null。
|
|
672
|
+
*/
|
|
673
|
+
load: async (id) => {
|
|
674
|
+
let _id = id;
|
|
675
|
+
if (_id.indexOf("/node_modules/") !== -1) {
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
if (_id.startsWith(VIRTUAL_PREFIX)) {
|
|
679
|
+
_id = _id.slice(VIRTUAL_PREFIX.length);
|
|
680
|
+
}
|
|
681
|
+
if (_id.startsWith("\0")) {
|
|
682
|
+
_id = _id.slice(1);
|
|
683
|
+
}
|
|
684
|
+
if (_id.startsWith(VIRTUAL_PREFIX2)) {
|
|
685
|
+
_id = _id.slice(VIRTUAL_PREFIX2.length);
|
|
686
|
+
}
|
|
687
|
+
const resolved = await resolveAbsoluteModuleId(_id);
|
|
688
|
+
if (!resolved) {
|
|
689
|
+
return null;
|
|
690
|
+
}
|
|
691
|
+
const [absoluteFilePath, entry] = resolved;
|
|
692
|
+
let isAllowed = false;
|
|
693
|
+
for (const allowedAbsolutePath of options.allowedAbsolutePaths) {
|
|
694
|
+
const relativePath = path.relative(
|
|
695
|
+
allowedAbsolutePath,
|
|
696
|
+
absoluteFilePath
|
|
697
|
+
);
|
|
698
|
+
if (relativePath && !relativePath.startsWith("..") && !path.isAbsolute(relativePath)) {
|
|
699
|
+
isAllowed = true;
|
|
700
|
+
break;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
if (!isAllowed) {
|
|
704
|
+
options.logger.error(
|
|
705
|
+
`\u8BD5\u56FE\u8BBF\u95EE\u7684 ${absoluteFilePath} \u6587\u4EF6\u5728\u8FD0\u884C\u8BBF\u95EE\u7684\u76EE\u5F55\u4E4B\u5916. See https://previewjs.com/docs/config and https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`
|
|
706
|
+
);
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
if (entry.kind !== "file") {
|
|
710
|
+
options.logger.error(`Unable to read file from ${absoluteFilePath}`);
|
|
711
|
+
return null;
|
|
712
|
+
}
|
|
713
|
+
const source = await entry.read();
|
|
714
|
+
const fileExtension = path.extname(absoluteFilePath);
|
|
715
|
+
if (!jsExtensions.has(fileExtension)) {
|
|
716
|
+
return source;
|
|
717
|
+
}
|
|
718
|
+
const moduleExtension = path.extname(id);
|
|
719
|
+
return {
|
|
720
|
+
code: (
|
|
721
|
+
// 对于.js或无扩展名的文件运行esbuild转换,因为可能包含JSX
|
|
722
|
+
// 否则,让插件决定是否使用esbuild
|
|
723
|
+
!id.includes("__previewjs_internal__") && (moduleExtension === "" || moduleExtension === ".js") ? (await transformWithEsbuild(source, absoluteFilePath, {
|
|
724
|
+
loader: absoluteFilePath.endsWith(".ts") ? "ts" : "tsx",
|
|
725
|
+
format: "esm",
|
|
726
|
+
target: "es2020",
|
|
727
|
+
sourcefile: path.relative(rootDir, absoluteFilePath),
|
|
728
|
+
...options.esbuildOptions
|
|
729
|
+
})).code : source
|
|
730
|
+
)
|
|
731
|
+
};
|
|
732
|
+
},
|
|
733
|
+
/**
|
|
734
|
+
* 转换模块代码。
|
|
735
|
+
* @param code - 模块代码。
|
|
736
|
+
* @param id - 模块ID。
|
|
737
|
+
* @returns 转换后的模块代码和源映射,如果不需要处理则返回null。
|
|
738
|
+
*/
|
|
739
|
+
transform: (code, id) => {
|
|
740
|
+
if (!id.startsWith(VIRTUAL_PREFIX)) {
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
return {
|
|
744
|
+
code,
|
|
745
|
+
map: {
|
|
746
|
+
mappings: "",
|
|
747
|
+
names: [],
|
|
748
|
+
sources: [],
|
|
749
|
+
version: 3
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
},
|
|
753
|
+
/**
|
|
754
|
+
* 处理热更新。
|
|
755
|
+
* 当文件发生变化时,更新虚拟模块。
|
|
756
|
+
* @param context - 热更新上下文。
|
|
757
|
+
* @returns 需要更新的模块节点数组,如果不需要处理则返回undefined。
|
|
758
|
+
*/
|
|
759
|
+
handleHotUpdate: async (context) => {
|
|
760
|
+
const moduleGraph = options.moduleGraph();
|
|
761
|
+
if (!moduleGraph) {
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
const filePath = path.relative(rootDir, context.file);
|
|
765
|
+
const absoluteFilePath = path.join(rootDir, filePath);
|
|
766
|
+
const entry = await reader.read(absoluteFilePath);
|
|
767
|
+
if (!entry || entry.kind !== "file") {
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
const virtualModuleId = VIRTUAL_PREFIX + toVitePath(absoluteFilePath);
|
|
771
|
+
const node = moduleGraph.getModuleById(virtualModuleId);
|
|
772
|
+
return node && [node];
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
async function resolveAbsoluteModuleId(id) {
|
|
776
|
+
return await resolveBaseFilePath(id) || await resolveBaseFilePath(path.join(rootDir, id));
|
|
777
|
+
}
|
|
778
|
+
async function resolveBaseFilePath(baseFilePath) {
|
|
779
|
+
for (const suffix of [
|
|
780
|
+
"",
|
|
781
|
+
...jsExtensions,
|
|
782
|
+
...[...jsExtensions].map((extension) => `${path.sep}index${extension}`)
|
|
783
|
+
]) {
|
|
784
|
+
const absoluteFilePath = `${baseFilePath}${suffix}`;
|
|
785
|
+
const entry = await reader.read(absoluteFilePath);
|
|
786
|
+
if (entry?.kind === "file") {
|
|
787
|
+
return [absoluteFilePath, entry];
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const inspectorServer = () => ({
|
|
795
|
+
name: "inspector-server-plugin",
|
|
796
|
+
configureServer(server) {
|
|
797
|
+
server.middlewares.use(launchEditorMiddleware);
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
var __defProp$2 = Object.defineProperty;
|
|
802
|
+
var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
803
|
+
var __publicField$2 = (obj, key, value) => {
|
|
804
|
+
__defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
805
|
+
return value;
|
|
806
|
+
};
|
|
807
|
+
var __accessCheck = (obj, member, msg) => {
|
|
808
|
+
if (!member.has(obj))
|
|
809
|
+
throw TypeError("Cannot " + msg);
|
|
810
|
+
};
|
|
811
|
+
var __privateGet = (obj, member, getter) => {
|
|
812
|
+
__accessCheck(obj, member, "read from private field");
|
|
813
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
814
|
+
};
|
|
815
|
+
var __privateAdd = (obj, member, value) => {
|
|
816
|
+
if (member.has(obj))
|
|
817
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
818
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
819
|
+
};
|
|
820
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
821
|
+
__accessCheck(obj, member, "write to private field");
|
|
822
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
823
|
+
return value;
|
|
824
|
+
};
|
|
825
|
+
var _state, _exclusively, _readerListener;
|
|
826
|
+
const POSTCSS_CONFIG_FILE = [
|
|
827
|
+
".postcssrc",
|
|
828
|
+
".postcssrc.json",
|
|
829
|
+
".postcssrc.yml",
|
|
830
|
+
".postcssrc.js",
|
|
831
|
+
".postcssrc.mjs",
|
|
832
|
+
".postcssrc.cjs",
|
|
833
|
+
".postcssrc.ts",
|
|
834
|
+
"postcss.config.js",
|
|
835
|
+
"postcss.config.mjs",
|
|
836
|
+
"postcss.config.cjs",
|
|
837
|
+
"postcss.config.ts"
|
|
838
|
+
];
|
|
839
|
+
const GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT = [
|
|
840
|
+
"index",
|
|
841
|
+
"global",
|
|
842
|
+
"globals",
|
|
843
|
+
"style",
|
|
844
|
+
"styles",
|
|
845
|
+
"app"
|
|
846
|
+
];
|
|
847
|
+
const GLOBAL_CSS_EXTS = ["css", "sass", "scss", "less", "styl", "stylus"];
|
|
848
|
+
const GLOBAL_CSS_FILE = GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT.flatMap(
|
|
849
|
+
(fileName) => GLOBAL_CSS_EXTS.map((ext) => `${fileName}.${ext}`)
|
|
850
|
+
);
|
|
851
|
+
const FILES_REQUIRING_VITE_RESTART = /* @__PURE__ */ new Set([
|
|
852
|
+
...PREVIEW_CONFIG_NAMES,
|
|
853
|
+
...FILES_REQUIRING_REDETECTION,
|
|
854
|
+
...POSTCSS_CONFIG_FILE,
|
|
855
|
+
...GLOBAL_CSS_FILE,
|
|
856
|
+
"vite.config.js",
|
|
857
|
+
"vite.config.ts",
|
|
858
|
+
// TODO: Make plugins contribute files requiring restart to make core agnostic of Svelte config files.
|
|
859
|
+
"svelte.config.js"
|
|
860
|
+
]);
|
|
861
|
+
async function endState(state) {
|
|
862
|
+
if (state?.kind === "starting") {
|
|
863
|
+
return state.promise;
|
|
864
|
+
}
|
|
865
|
+
return state;
|
|
866
|
+
}
|
|
867
|
+
class ViteManager {
|
|
868
|
+
constructor(options) {
|
|
869
|
+
this.options = options;
|
|
870
|
+
__publicField$2(this, "middleware");
|
|
871
|
+
__privateAdd(this, _state, null);
|
|
872
|
+
__privateAdd(this, _exclusively, void 0);
|
|
873
|
+
__privateAdd(this, _readerListener, {
|
|
874
|
+
onChange: (absoluteFilePath, info) => {
|
|
875
|
+
this.onFileChanged(path.resolve(absoluteFilePath), info).catch(
|
|
876
|
+
(e) => this.options.logger.error(e)
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
});
|
|
880
|
+
const router = express.Router();
|
|
881
|
+
router.use(async (req, res, next) => {
|
|
882
|
+
const state = await endState(__privateGet(this, _state));
|
|
883
|
+
if (!state || state.kind === "error") {
|
|
884
|
+
return next();
|
|
885
|
+
}
|
|
886
|
+
try {
|
|
887
|
+
state.viteServer.middlewares(req, res, next);
|
|
888
|
+
} catch (e) {
|
|
889
|
+
this.options.logger.error(`Vite middleware error: ${e}`);
|
|
890
|
+
res.status(500).end(`Vite middleware error: ${e}`);
|
|
891
|
+
}
|
|
892
|
+
});
|
|
893
|
+
this.middleware = router;
|
|
894
|
+
__privateSet(this, _exclusively, exclusivePromiseRunner());
|
|
895
|
+
}
|
|
896
|
+
get state() {
|
|
897
|
+
return __privateGet(this, _state);
|
|
898
|
+
}
|
|
899
|
+
async loadIndexHtml(url, id) {
|
|
900
|
+
return __privateGet(this, _exclusively).call(this, async () => {
|
|
901
|
+
try {
|
|
902
|
+
const state = await endState(__privateGet(this, _state));
|
|
903
|
+
if (!state) {
|
|
904
|
+
return generateHtmlError("Vite server is not running");
|
|
905
|
+
}
|
|
906
|
+
if (state.kind === "error") {
|
|
907
|
+
return generateHtmlError(state.error);
|
|
908
|
+
}
|
|
909
|
+
const template = await fs$1.readFile(
|
|
910
|
+
this.options.shadowHtmlFilePath,
|
|
911
|
+
"utf-8"
|
|
912
|
+
);
|
|
913
|
+
const { config, viteServer } = state;
|
|
914
|
+
const { filePath, name: previewableName } = decodePreviewableId(id);
|
|
915
|
+
const previewablePath = filePath.replace(/\\/g, "/");
|
|
916
|
+
const wrapper = config.wrapper;
|
|
917
|
+
const wrapperPath = wrapper && await fs$1.pathExists(path.join(this.options.rootDir, wrapper.path)) ? wrapper.path.replace(/\\/g, "/") : null;
|
|
918
|
+
return await viteServer.transformIndexHtml(
|
|
919
|
+
url,
|
|
920
|
+
// 将占位符替换为实际内容, 注入 iframe/preview/__previewjs_internal__/preview.js
|
|
921
|
+
// 将参数进行 base64 编码, 以 url 参数形式传递到 script 标签中
|
|
922
|
+
template.replace(
|
|
923
|
+
"<!-- %OPTIONAL_HEAD_CONTENT% -->",
|
|
924
|
+
`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(
|
|
925
|
+
JSON.stringify({
|
|
926
|
+
previewablePath,
|
|
927
|
+
previewableName,
|
|
928
|
+
wrapperPath,
|
|
929
|
+
wrapperName: wrapper?.componentName || null,
|
|
930
|
+
detectedGlobalCssFilePaths: config.detectedGlobalCssFilePaths
|
|
931
|
+
}),
|
|
932
|
+
"utf8"
|
|
933
|
+
).toString("base64url")}"><\/script>`
|
|
934
|
+
)
|
|
935
|
+
);
|
|
936
|
+
} catch (e) {
|
|
937
|
+
return generateHtmlError(`${e}`);
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
// Note: this is guaranteed not to throw.
|
|
942
|
+
async start() {
|
|
943
|
+
let setEndState;
|
|
944
|
+
__privateSet(this, _state, {
|
|
945
|
+
kind: "starting",
|
|
946
|
+
promise: new Promise((resolve) => {
|
|
947
|
+
setEndState = (state) => {
|
|
948
|
+
__privateSet(this, _state, state);
|
|
949
|
+
resolve(state);
|
|
950
|
+
};
|
|
951
|
+
})
|
|
952
|
+
});
|
|
953
|
+
this.options.reader.listeners.add(__privateGet(this, _readerListener));
|
|
954
|
+
try {
|
|
955
|
+
process.chdir(this.options.rootDir);
|
|
956
|
+
const configFromProject = await readConfig(
|
|
957
|
+
this.options.rootDir,
|
|
958
|
+
viteLogLevelFromPinoLogger(this.options.logger)
|
|
959
|
+
);
|
|
960
|
+
const globalCssAbsoluteFilePaths = await findFiles(
|
|
961
|
+
this.options.rootDir,
|
|
962
|
+
`**/@(${GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT.join(
|
|
963
|
+
"|"
|
|
964
|
+
)}).@(${GLOBAL_CSS_EXTS.join("|")})`,
|
|
965
|
+
{
|
|
966
|
+
maxDepth: 3
|
|
967
|
+
}
|
|
968
|
+
);
|
|
969
|
+
const config = {
|
|
970
|
+
...configFromProject,
|
|
971
|
+
wrapper: configFromProject.wrapper || {
|
|
972
|
+
path: this.options.frameworkPlugin.defaultWrapperPath
|
|
973
|
+
},
|
|
974
|
+
detectedGlobalCssFilePaths: globalCssAbsoluteFilePaths.map(
|
|
975
|
+
(absoluteFilePath) => path.relative(this.options.rootDir, absoluteFilePath)
|
|
976
|
+
)
|
|
977
|
+
};
|
|
978
|
+
const tsInferredAlias = [];
|
|
979
|
+
let tsConfig = null;
|
|
980
|
+
for (const potentialTsConfigFileName of [
|
|
981
|
+
"tsconfig.json",
|
|
982
|
+
"jsconfig.json"
|
|
983
|
+
]) {
|
|
984
|
+
const potentialTsConfigFilePath = path.join(
|
|
985
|
+
this.options.rootDir,
|
|
986
|
+
potentialTsConfigFileName
|
|
987
|
+
);
|
|
988
|
+
try {
|
|
989
|
+
if (await fs$1.pathExists(potentialTsConfigFilePath)) {
|
|
990
|
+
const unsafeTsConfig = loadTsconfig(potentialTsConfigFilePath) || null;
|
|
991
|
+
if (unsafeTsConfig) {
|
|
992
|
+
tsConfig = validTsConfig.parse(unsafeTsConfig);
|
|
993
|
+
break;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
} catch (e) {
|
|
997
|
+
this.options.logger.warn(
|
|
998
|
+
`Unable to load tsconfig from ${potentialTsConfigFilePath}: ${e}`
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
this.options.logger.debug(
|
|
1003
|
+
`Loaded ts/jsconfig: ${JSON.stringify(tsConfig || null, null, 2)}`
|
|
1004
|
+
);
|
|
1005
|
+
const baseUrl = tsConfig?.compilerOptions?.baseUrl || "";
|
|
1006
|
+
const tsConfigPaths = tsConfig?.compilerOptions?.paths || {};
|
|
1007
|
+
let baseAlias = baseUrl.startsWith("./") ? baseUrl.substring(1) : baseUrl;
|
|
1008
|
+
if (baseAlias && !baseAlias.endsWith("/")) {
|
|
1009
|
+
baseAlias += "/";
|
|
1010
|
+
}
|
|
1011
|
+
for (const [match, mapping] of Object.entries(tsConfigPaths)) {
|
|
1012
|
+
const firstMapping = mapping[0];
|
|
1013
|
+
if (!firstMapping) {
|
|
1014
|
+
continue;
|
|
1015
|
+
}
|
|
1016
|
+
const matchNoWildcard = match.endsWith("/*") ? match.slice(0, match.length - 2) : match;
|
|
1017
|
+
const firstMappingNoWildcard = firstMapping.endsWith("/*") ? firstMapping.slice(0, firstMapping.length - 2) : firstMapping;
|
|
1018
|
+
tsInferredAlias.push({
|
|
1019
|
+
find: matchNoWildcard,
|
|
1020
|
+
replacement: path.join(
|
|
1021
|
+
this.options.rootDir,
|
|
1022
|
+
baseUrl,
|
|
1023
|
+
firstMappingNoWildcard
|
|
1024
|
+
)
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
const existingViteConfig = await vite.loadConfigFromFile(
|
|
1028
|
+
{
|
|
1029
|
+
command: "serve",
|
|
1030
|
+
mode: "development"
|
|
1031
|
+
},
|
|
1032
|
+
void 0,
|
|
1033
|
+
this.options.rootDir
|
|
1034
|
+
);
|
|
1035
|
+
const defaultLogger = vite.createLogger(
|
|
1036
|
+
viteLogLevelFromPinoLogger(this.options.logger)
|
|
1037
|
+
);
|
|
1038
|
+
const frameworkPluginViteConfig = this.options.frameworkPlugin.viteConfig(
|
|
1039
|
+
await flattenPlugins([
|
|
1040
|
+
...existingViteConfig?.config.plugins || [],
|
|
1041
|
+
...config.vite?.plugins || []
|
|
1042
|
+
])
|
|
1043
|
+
);
|
|
1044
|
+
const publicDir = config.vite?.publicDir || existingViteConfig?.config.publicDir || frameworkPluginViteConfig.publicDir || config.publicDir || "public";
|
|
1045
|
+
const plugins = replaceHandleHotUpdate(
|
|
1046
|
+
this.options.reader,
|
|
1047
|
+
await flattenPlugins([
|
|
1048
|
+
viteTsconfigPaths({
|
|
1049
|
+
root: this.options.rootDir
|
|
1050
|
+
}),
|
|
1051
|
+
previewScriptPlugin(),
|
|
1052
|
+
virtualPlugin({
|
|
1053
|
+
logger: this.options.logger,
|
|
1054
|
+
reader: this.options.reader,
|
|
1055
|
+
rootDir: this.options.rootDir,
|
|
1056
|
+
allowedAbsolutePaths: config.vite?.server?.fs?.allow || existingViteConfig?.config.server?.fs?.allow || [
|
|
1057
|
+
searchForWorkspaceRoot(this.options.rootDir)
|
|
1058
|
+
],
|
|
1059
|
+
moduleGraph: () => {
|
|
1060
|
+
if (__privateGet(this, _state)?.kind === "running") {
|
|
1061
|
+
return __privateGet(this, _state).viteServer.moduleGraph;
|
|
1062
|
+
}
|
|
1063
|
+
return null;
|
|
1064
|
+
},
|
|
1065
|
+
esbuildOptions: frameworkPluginViteConfig.esbuild || {}
|
|
1066
|
+
}),
|
|
1067
|
+
localEval(),
|
|
1068
|
+
inspectorServer(),
|
|
1069
|
+
// 增加react-inspector-plugin插件
|
|
1070
|
+
invalidateStoriesModulesOnUpdate(),
|
|
1071
|
+
fakeExportedTypesPlugin({
|
|
1072
|
+
readFile: (absoluteFilePath) => this.options.reader.read(absoluteFilePath).then((entry) => {
|
|
1073
|
+
if (entry?.kind !== "file") {
|
|
1074
|
+
return null;
|
|
1075
|
+
}
|
|
1076
|
+
return entry.read();
|
|
1077
|
+
})
|
|
1078
|
+
}),
|
|
1079
|
+
// forced cast rollup.plugin to vite.plugin
|
|
1080
|
+
cssModulesWithoutSuffixPlugin(),
|
|
1081
|
+
publicAssetImportPluginPlugin({
|
|
1082
|
+
rootDir: this.options.rootDir,
|
|
1083
|
+
publicDir
|
|
1084
|
+
}),
|
|
1085
|
+
frameworkPluginViteConfig.plugins
|
|
1086
|
+
])
|
|
1087
|
+
);
|
|
1088
|
+
this.options.logger.debug("Creating Vite server");
|
|
1089
|
+
const viteServerPromise = vite.createServer({
|
|
1090
|
+
...frameworkPluginViteConfig,
|
|
1091
|
+
...existingViteConfig?.config,
|
|
1092
|
+
...config.vite,
|
|
1093
|
+
configFile: false,
|
|
1094
|
+
root: this.options.rootDir,
|
|
1095
|
+
server: {
|
|
1096
|
+
middlewareMode: true,
|
|
1097
|
+
hmr: {
|
|
1098
|
+
overlay: false,
|
|
1099
|
+
server: this.options.server,
|
|
1100
|
+
clientPort: this.options.clientPort || this.options.port,
|
|
1101
|
+
...typeof config.vite?.server?.hmr === "object" ? config.vite?.server?.hmr : {}
|
|
1102
|
+
},
|
|
1103
|
+
fs: {
|
|
1104
|
+
strict: false,
|
|
1105
|
+
...config.vite?.server?.fs || {}
|
|
1106
|
+
},
|
|
1107
|
+
...config.vite?.server
|
|
1108
|
+
},
|
|
1109
|
+
customLogger: {
|
|
1110
|
+
info: defaultLogger.info,
|
|
1111
|
+
warn: defaultLogger.warn,
|
|
1112
|
+
error: (msg, options) => {
|
|
1113
|
+
if (!msg.startsWith("\x1B[31mInternal server error")) {
|
|
1114
|
+
if (__privateGet(this, _state)?.kind === "running") {
|
|
1115
|
+
__privateGet(this, _state).viteServer.ws.send({
|
|
1116
|
+
type: "error",
|
|
1117
|
+
err: {
|
|
1118
|
+
message: msg,
|
|
1119
|
+
stack: ""
|
|
1120
|
+
}
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
defaultLogger.error(msg, options);
|
|
1125
|
+
},
|
|
1126
|
+
warnOnce: defaultLogger.warnOnce,
|
|
1127
|
+
clearScreen: () => {
|
|
1128
|
+
},
|
|
1129
|
+
hasWarned: defaultLogger.hasWarned,
|
|
1130
|
+
hasErrorLogged: defaultLogger.hasErrorLogged
|
|
1131
|
+
},
|
|
1132
|
+
clearScreen: false,
|
|
1133
|
+
cacheDir: config.vite?.cacheDir || existingViteConfig?.config.cacheDir || this.options.cacheDir,
|
|
1134
|
+
publicDir,
|
|
1135
|
+
plugins,
|
|
1136
|
+
define: {
|
|
1137
|
+
__filename: void 0,
|
|
1138
|
+
__dirname: void 0,
|
|
1139
|
+
process: void 0,
|
|
1140
|
+
...frameworkPluginViteConfig.define,
|
|
1141
|
+
...existingViteConfig?.config.define,
|
|
1142
|
+
...config.vite?.define
|
|
1143
|
+
},
|
|
1144
|
+
resolve: {
|
|
1145
|
+
...existingViteConfig?.config.resolve,
|
|
1146
|
+
...config.vite?.resolve,
|
|
1147
|
+
alias: [
|
|
1148
|
+
// First defined rules are applied first, therefore highest priority should come first.
|
|
1149
|
+
...viteAliasToRollupAliasEntries(config.vite?.resolve?.alias),
|
|
1150
|
+
...viteAliasToRollupAliasEntries(config.alias),
|
|
1151
|
+
...viteAliasToRollupAliasEntries(
|
|
1152
|
+
existingViteConfig?.config.resolve?.alias
|
|
1153
|
+
),
|
|
1154
|
+
...tsInferredAlias,
|
|
1155
|
+
{
|
|
1156
|
+
find: /^~(.*)/,
|
|
1157
|
+
replacement: `${baseAlias}$1`
|
|
1158
|
+
},
|
|
1159
|
+
{
|
|
1160
|
+
find: "@",
|
|
1161
|
+
replacement: baseAlias
|
|
1162
|
+
},
|
|
1163
|
+
...viteAliasToRollupAliasEntries(
|
|
1164
|
+
frameworkPluginViteConfig.resolve?.alias
|
|
1165
|
+
)
|
|
1166
|
+
]
|
|
1167
|
+
}
|
|
1168
|
+
});
|
|
1169
|
+
const viteServer = await viteServerPromise;
|
|
1170
|
+
setEndState({
|
|
1171
|
+
kind: "running",
|
|
1172
|
+
config,
|
|
1173
|
+
viteServer
|
|
1174
|
+
});
|
|
1175
|
+
this.options.logger.debug("Done starting Vite server");
|
|
1176
|
+
} catch (e) {
|
|
1177
|
+
this.options.logger.error(`Vite startup error: ${e}`);
|
|
1178
|
+
setEndState({
|
|
1179
|
+
kind: "error",
|
|
1180
|
+
error: e.stack || e.message
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
return __privateGet(this, _state).promise;
|
|
1184
|
+
}
|
|
1185
|
+
async stop({ restart } = { restart: false }) {
|
|
1186
|
+
await __privateGet(this, _exclusively).call(this, async () => {
|
|
1187
|
+
this.options.reader.listeners.remove(__privateGet(this, _readerListener));
|
|
1188
|
+
const state = await endState(__privateGet(this, _state));
|
|
1189
|
+
if (state?.kind === "running") {
|
|
1190
|
+
await state.viteServer.close();
|
|
1191
|
+
}
|
|
1192
|
+
if (restart) {
|
|
1193
|
+
return this.start();
|
|
1194
|
+
}
|
|
1195
|
+
return __privateSet(this, _state, null);
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
async onFileChanged(absoluteFilePath, info) {
|
|
1199
|
+
const state = await endState(this.state);
|
|
1200
|
+
if (!state) {
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
if (!info.virtual) {
|
|
1204
|
+
this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(
|
|
1205
|
+
path.relative(this.options.rootDir, absoluteFilePath)
|
|
1206
|
+
);
|
|
1207
|
+
if (FILES_REQUIRING_VITE_RESTART.has(path.basename(absoluteFilePath))) {
|
|
1208
|
+
this.options.logger.info(
|
|
1209
|
+
"New dependencies were detected. Restarting..."
|
|
1210
|
+
);
|
|
1211
|
+
await this.stop({ restart: true });
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
if (state.kind !== "running") {
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
const { viteServer, config } = state;
|
|
1219
|
+
if (info.virtual) {
|
|
1220
|
+
const modules = await viteServer.moduleGraph.getModulesByFile(
|
|
1221
|
+
toVitePath(absoluteFilePath)
|
|
1222
|
+
);
|
|
1223
|
+
for (const module of modules || []) {
|
|
1224
|
+
if (!module.id) {
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
try {
|
|
1228
|
+
const loaded = await viteServer.pluginContainer.load(module.id);
|
|
1229
|
+
if (!loaded) {
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
const source = typeof loaded === "object" ? loaded.code : loaded;
|
|
1233
|
+
await viteServer.pluginContainer.transform(source, module.id);
|
|
1234
|
+
} catch {
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
for (const onChange of viteServer.watcher.listeners("change")) {
|
|
1239
|
+
onChange(absoluteFilePath);
|
|
1240
|
+
}
|
|
1241
|
+
} else if (config.wrapper && absoluteFilePath === path.resolve(this.options.rootDir, config.wrapper.path)) {
|
|
1242
|
+
viteServer.moduleGraph.invalidateAll();
|
|
1243
|
+
viteServer.ws.send({
|
|
1244
|
+
type: "full-reload"
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
_state = new WeakMap();
|
|
1250
|
+
_exclusively = new WeakMap();
|
|
1251
|
+
_readerListener = new WeakMap();
|
|
1252
|
+
function viteAliasToRollupAliasEntries(alias) {
|
|
1253
|
+
if (!alias) {
|
|
1254
|
+
return [];
|
|
1255
|
+
}
|
|
1256
|
+
if (Array.isArray(alias)) {
|
|
1257
|
+
return alias;
|
|
1258
|
+
}
|
|
1259
|
+
return Object.entries(alias).map(([find, replacement]) => ({
|
|
1260
|
+
find,
|
|
1261
|
+
replacement
|
|
1262
|
+
}));
|
|
1263
|
+
}
|
|
1264
|
+
async function flattenPlugins(pluginOptions) {
|
|
1265
|
+
const plugins = [];
|
|
1266
|
+
for (const pluginOption of await Promise.all(pluginOptions)) {
|
|
1267
|
+
if (!pluginOption) {
|
|
1268
|
+
continue;
|
|
1269
|
+
}
|
|
1270
|
+
if (Array.isArray(pluginOption)) {
|
|
1271
|
+
plugins.push(...await flattenPlugins(pluginOption));
|
|
1272
|
+
} else {
|
|
1273
|
+
plugins.push(pluginOption);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
return plugins;
|
|
1277
|
+
}
|
|
1278
|
+
function viteLogLevelFromPinoLogger(logger) {
|
|
1279
|
+
switch (logger.level) {
|
|
1280
|
+
case "fatal":
|
|
1281
|
+
return "silent";
|
|
1282
|
+
case "error":
|
|
1283
|
+
return "error";
|
|
1284
|
+
case "warn":
|
|
1285
|
+
return "warn";
|
|
1286
|
+
case "info":
|
|
1287
|
+
return "info";
|
|
1288
|
+
case "debug":
|
|
1289
|
+
return "info";
|
|
1290
|
+
case "trace":
|
|
1291
|
+
return "info";
|
|
1292
|
+
case "silent":
|
|
1293
|
+
return "silent";
|
|
1294
|
+
default:
|
|
1295
|
+
logger.warn(`Unknown log level: ${logger.level}`);
|
|
1296
|
+
return "info";
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
function replaceHandleHotUpdate(reader, plugins) {
|
|
1300
|
+
return plugins.map(async (plugin) => {
|
|
1301
|
+
if (!plugin.handleHotUpdate) {
|
|
1302
|
+
return plugin;
|
|
1303
|
+
}
|
|
1304
|
+
const handleHotUpdate = typeof plugin.handleHotUpdate === "function" ? plugin.handleHotUpdate : plugin.handleHotUpdate.handler;
|
|
1305
|
+
return {
|
|
1306
|
+
...plugin,
|
|
1307
|
+
handleHotUpdate: async (ctx) => {
|
|
1308
|
+
await handleHotUpdate({
|
|
1309
|
+
...ctx,
|
|
1310
|
+
read: async () => {
|
|
1311
|
+
const entry = await reader.read(ctx.file);
|
|
1312
|
+
if (entry?.kind !== "file") {
|
|
1313
|
+
return ctx.read();
|
|
1314
|
+
}
|
|
1315
|
+
return entry.read();
|
|
1316
|
+
}
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
const validTsConfig = z.object({
|
|
1323
|
+
compilerOptions: z.object({
|
|
1324
|
+
baseUrl: z.string().optional(),
|
|
1325
|
+
paths: z.record(z.array(z.string())).optional()
|
|
1326
|
+
}).optional()
|
|
1327
|
+
});
|
|
1328
|
+
|
|
1329
|
+
var __defProp$1 = Object.defineProperty;
|
|
1330
|
+
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
1331
|
+
var __publicField$1 = (obj, key, value) => {
|
|
1332
|
+
__defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1333
|
+
return value;
|
|
1334
|
+
};
|
|
1335
|
+
class Previewer {
|
|
1336
|
+
constructor(options) {
|
|
1337
|
+
this.options = options;
|
|
1338
|
+
__publicField$1(this, "transformingReader");
|
|
1339
|
+
__publicField$1(this, "viteManager", null);
|
|
1340
|
+
__publicField$1(this, "status", { kind: "stopped" });
|
|
1341
|
+
__publicField$1(this, "disposeObserver", null);
|
|
1342
|
+
this.transformingReader = createStackedReader([
|
|
1343
|
+
options.reader,
|
|
1344
|
+
createFileSystemReader({
|
|
1345
|
+
mapping: {
|
|
1346
|
+
from: options.frameworkPlugin.previewDirPath,
|
|
1347
|
+
to: path.join(options.rootDir, "__previewjs_internal__", "renderer")
|
|
1348
|
+
},
|
|
1349
|
+
watch: false
|
|
1350
|
+
}),
|
|
1351
|
+
createFileSystemReader({
|
|
1352
|
+
mapping: {
|
|
1353
|
+
from: options.previewDirPath,
|
|
1354
|
+
to: options.rootDir
|
|
1355
|
+
},
|
|
1356
|
+
watch: false
|
|
1357
|
+
})
|
|
1358
|
+
]);
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* 启动预览服务器。
|
|
1362
|
+
* 如果预览服务器已经在启动中,该方法将等待启动完成。
|
|
1363
|
+
* 如果预览服务器已经启动,该方法将立即返回。
|
|
1364
|
+
* 如果预览服务器已经在停止中,该方法将等待停止完成,然后重新启动。
|
|
1365
|
+
* 如果预览服务器已经停止,该方法将启动预览服务器。
|
|
1366
|
+
*/
|
|
1367
|
+
async start() {
|
|
1368
|
+
const statusBeforeStart = this.status;
|
|
1369
|
+
switch (statusBeforeStart.kind) {
|
|
1370
|
+
case "starting":
|
|
1371
|
+
try {
|
|
1372
|
+
await statusBeforeStart.promise;
|
|
1373
|
+
} catch (e) {
|
|
1374
|
+
this.options.logger.error(e);
|
|
1375
|
+
this.status = {
|
|
1376
|
+
kind: "stopped"
|
|
1377
|
+
};
|
|
1378
|
+
await this.startFromStopped();
|
|
1379
|
+
}
|
|
1380
|
+
break;
|
|
1381
|
+
case "started":
|
|
1382
|
+
break;
|
|
1383
|
+
case "stopping":
|
|
1384
|
+
try {
|
|
1385
|
+
await statusBeforeStart.promise;
|
|
1386
|
+
} catch (e) {
|
|
1387
|
+
this.options.logger.error(e);
|
|
1388
|
+
this.status = {
|
|
1389
|
+
kind: "stopped"
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
await this.start();
|
|
1393
|
+
break;
|
|
1394
|
+
case "stopped":
|
|
1395
|
+
await this.startFromStopped();
|
|
1396
|
+
break;
|
|
1397
|
+
default:
|
|
1398
|
+
throw assertNever(statusBeforeStart);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* 从停止状态启动
|
|
1403
|
+
*/
|
|
1404
|
+
async startFromStopped() {
|
|
1405
|
+
this.status = {
|
|
1406
|
+
kind: "starting",
|
|
1407
|
+
promise: (async () => {
|
|
1408
|
+
const router = express.Router();
|
|
1409
|
+
router.use((_req, res, next) => {
|
|
1410
|
+
res.setHeader("Cache-Control", "max-age=0, must-revalidate");
|
|
1411
|
+
next();
|
|
1412
|
+
});
|
|
1413
|
+
router.use(this.options.middlewares);
|
|
1414
|
+
router.get(/^\/.*:[^/]+\/$/, async (req, res, next) => {
|
|
1415
|
+
const accept = req.header("Accept");
|
|
1416
|
+
if (req.url.includes("?html-proxy")) {
|
|
1417
|
+
next();
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
if (accept === "text/x-vite-ping") {
|
|
1421
|
+
res.writeHead(204).end();
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
const previewableId = req.path.substring(1, req.path.length - 1);
|
|
1425
|
+
if (!this.viteManager) {
|
|
1426
|
+
res.status(404).end("Vite\u670D\u52A1\u5668\u672A\u542F\u52A8");
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
res.status(200).set({ "Content-Type": "text/html" }).end(
|
|
1430
|
+
await this.viteManager.loadIndexHtml(
|
|
1431
|
+
req.originalUrl,
|
|
1432
|
+
previewableId
|
|
1433
|
+
)
|
|
1434
|
+
);
|
|
1435
|
+
});
|
|
1436
|
+
router.use("/ping", async (req, res) => {
|
|
1437
|
+
res.json(
|
|
1438
|
+
JSON.stringify({
|
|
1439
|
+
pong: "match!"
|
|
1440
|
+
})
|
|
1441
|
+
);
|
|
1442
|
+
});
|
|
1443
|
+
router.use((req, res, next) => {
|
|
1444
|
+
this.viteManager?.middleware(req, res, next);
|
|
1445
|
+
});
|
|
1446
|
+
if (this.transformingReader.observe) {
|
|
1447
|
+
try {
|
|
1448
|
+
this.disposeObserver = await this.transformingReader.observe(
|
|
1449
|
+
this.options.rootDir
|
|
1450
|
+
);
|
|
1451
|
+
} catch (error) {
|
|
1452
|
+
this.options.logger.error("\u542F\u52A8\u6587\u4EF6\u7CFB\u7EDF\u76D1\u542C\u5931\u8D25:", error);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
const { server, disposeHttpServer } = await this.options.getHttpServer(
|
|
1456
|
+
router
|
|
1457
|
+
);
|
|
1458
|
+
this.options.logger.debug("\u542F\u52A8 Vite manager ...");
|
|
1459
|
+
this.viteManager = new ViteManager({
|
|
1460
|
+
rootDir: this.options.rootDir,
|
|
1461
|
+
shadowHtmlFilePath: path.join(
|
|
1462
|
+
this.options.previewDirPath,
|
|
1463
|
+
"index.html"
|
|
1464
|
+
),
|
|
1465
|
+
reader: this.transformingReader,
|
|
1466
|
+
cacheDir: path.join(getCacheDir(this.options.rootDir), "vite"),
|
|
1467
|
+
logger: this.options.logger,
|
|
1468
|
+
frameworkPlugin: this.options.frameworkPlugin,
|
|
1469
|
+
server,
|
|
1470
|
+
port: this.options.port,
|
|
1471
|
+
clientPort: this.options.clientPort
|
|
1472
|
+
});
|
|
1473
|
+
this.viteManager.start();
|
|
1474
|
+
this.options.logger.debug("\u9884\u89C8\u670D\u52A1\u5DF2\u5C31\u7EEA");
|
|
1475
|
+
this.status = {
|
|
1476
|
+
kind: "started",
|
|
1477
|
+
onStop: disposeHttpServer
|
|
1478
|
+
};
|
|
1479
|
+
})()
|
|
1480
|
+
};
|
|
1481
|
+
await this.status.promise;
|
|
1482
|
+
for (let i = 0; ; i++) {
|
|
1483
|
+
try {
|
|
1484
|
+
await axios.get(`http://localhost:${this.options.port}`);
|
|
1485
|
+
break;
|
|
1486
|
+
} catch (e) {
|
|
1487
|
+
if (i === 10) {
|
|
1488
|
+
throw e;
|
|
1489
|
+
}
|
|
1490
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* 停止预览服务器
|
|
1496
|
+
* @returns
|
|
1497
|
+
*/
|
|
1498
|
+
async stop() {
|
|
1499
|
+
if (this.status.kind === "starting") {
|
|
1500
|
+
try {
|
|
1501
|
+
await this.status.promise;
|
|
1502
|
+
} catch {
|
|
1503
|
+
this.status = {
|
|
1504
|
+
kind: "stopped"
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
if (this.status.kind !== "started") {
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
const onStop = this.status.onStop;
|
|
1512
|
+
this.status = {
|
|
1513
|
+
kind: "stopping",
|
|
1514
|
+
promise: (async () => {
|
|
1515
|
+
await this.disposeObserver?.();
|
|
1516
|
+
this.disposeObserver = null;
|
|
1517
|
+
await this.viteManager?.stop();
|
|
1518
|
+
this.viteManager = null;
|
|
1519
|
+
await onStop();
|
|
1520
|
+
this.status = {
|
|
1521
|
+
kind: "stopped"
|
|
1522
|
+
};
|
|
1523
|
+
})()
|
|
1524
|
+
};
|
|
1525
|
+
await this.status.promise;
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
var __defProp = Object.defineProperty;
|
|
1530
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
1531
|
+
var __publicField = (obj, key, value) => {
|
|
1532
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1533
|
+
return value;
|
|
1534
|
+
};
|
|
1535
|
+
class ApiRouter {
|
|
1536
|
+
/**
|
|
1537
|
+
* 构造函数,初始化 ApiRouter 实例。
|
|
1538
|
+
* @param logger - 用于记录日志的 Logger 实例。
|
|
1539
|
+
*/
|
|
1540
|
+
constructor(logger) {
|
|
1541
|
+
this.logger = logger;
|
|
1542
|
+
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
1543
|
+
__publicField(this, "handlers", /* @__PURE__ */ new Map());
|
|
1544
|
+
/**
|
|
1545
|
+
* 注册一个 RPC 端点及其处理函数。
|
|
1546
|
+
* @param endpoint - RPC 端点对象。
|
|
1547
|
+
* @param handler - 处理该端点请求的函数。
|
|
1548
|
+
*/
|
|
1549
|
+
__publicField(this, "registerRPC", (endpoint, handler) => {
|
|
1550
|
+
if (this.handlers.has(endpoint.path)) {
|
|
1551
|
+
throw new Error(
|
|
1552
|
+
`\u7AEF\u70B9 '${endpoint.path}' \u5DF2\u7ECF\u6CE8\u518C\u4E86 handler\uFF0C\u662F\u5426\u91CD\u590D\u6CE8\u518C\uFF1F`
|
|
1553
|
+
);
|
|
1554
|
+
}
|
|
1555
|
+
this.handlers.set(endpoint.path, handler);
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* 处理传入的 RPC 请求。
|
|
1560
|
+
* @param path - 请求的路径。
|
|
1561
|
+
* @param request - 请求的数据。
|
|
1562
|
+
* @returns 包含响应结果的包装对象。
|
|
1563
|
+
*/
|
|
1564
|
+
async handle(path, request) {
|
|
1565
|
+
const handler = this.handlers.get(path);
|
|
1566
|
+
if (!handler) {
|
|
1567
|
+
return {
|
|
1568
|
+
kind: "error",
|
|
1569
|
+
message: `\u8DEF\u5F84 '${path}' \u6CA1\u6709\u6CE8\u518C\u5BF9\u5E94\u7684 handler`
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
this.logger.debug(`RPC ${path} invoked`);
|
|
1573
|
+
try {
|
|
1574
|
+
const response = await handler(request);
|
|
1575
|
+
return {
|
|
1576
|
+
kind: "success",
|
|
1577
|
+
response
|
|
1578
|
+
};
|
|
1579
|
+
} catch (e) {
|
|
1580
|
+
this.logger.error(`RPC ${path} failed: ${e}`);
|
|
1581
|
+
if (e instanceof Error) {
|
|
1582
|
+
return {
|
|
1583
|
+
kind: "error",
|
|
1584
|
+
message: e.message
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
return {
|
|
1588
|
+
kind: "error",
|
|
1589
|
+
message: `${e}`
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
async function findCompatiblePlugin(logger, rootDir, frameworkPlugins) {
|
|
1596
|
+
const dependencies = await extractPackageDependencies(logger, rootDir);
|
|
1597
|
+
for (const candidate of frameworkPlugins) {
|
|
1598
|
+
if (!candidate.info) {
|
|
1599
|
+
continue;
|
|
1600
|
+
}
|
|
1601
|
+
if (await candidate.isCompatible(dependencies)) {
|
|
1602
|
+
return candidate.info?.name;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
return null;
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
const { pino: createLogger } = pino;
|
|
1609
|
+
const prettyLogger = PinoPretty;
|
|
1610
|
+
const require = createRequire(import.meta.url);
|
|
1611
|
+
process.on("uncaughtException", (e) => {
|
|
1612
|
+
console.error("Core \u9047\u5230\u672A\u6355\u83B7\u7684\u5F02\u5E38", e);
|
|
1613
|
+
});
|
|
1614
|
+
process.on("unhandledRejection", (e) => {
|
|
1615
|
+
console.error("Core \u9047\u5230\u672A\u5904\u7406\u7684 Promise \u5BF9\u8C61", e);
|
|
1616
|
+
});
|
|
1617
|
+
async function createWorkspace({
|
|
1618
|
+
rootDir,
|
|
1619
|
+
frameworkPlugin: frameworkPluginFactory,
|
|
1620
|
+
logger = createLogger(
|
|
1621
|
+
{ level: process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase() || "warn" },
|
|
1622
|
+
prettyLogger({ colorize: true })
|
|
1623
|
+
),
|
|
1624
|
+
reader = createFileSystemReader(),
|
|
1625
|
+
onServerStart = () => Promise.resolve({})
|
|
1626
|
+
}) {
|
|
1627
|
+
const expectedPluginApiVersion = 5;
|
|
1628
|
+
if (!frameworkPluginFactory.info) {
|
|
1629
|
+
throw new Error(
|
|
1630
|
+
"\u63D0\u4F9B\u7684 framework plugin \u4E0E\u5F53\u524D\u7248\u672C Preview.js \u4E0D\u9002\u914D. \u8BF7\u5347\u7EA7."
|
|
1631
|
+
);
|
|
1632
|
+
}
|
|
1633
|
+
if (frameworkPluginFactory.info.apiVersion > expectedPluginApiVersion) {
|
|
1634
|
+
throw new Error(
|
|
1635
|
+
`Preview.js \u7684 framework plugin ${frameworkPluginFactory.info.name} \u592A\u65B0\u4E86. \u8BF7\u5347\u7EA7 Preview.js \u6216\u8005\u4F7F\u7528 ${frameworkPluginFactory.info.name} \u7684\u8F83\u65E9\u7248\u672C.`
|
|
1636
|
+
);
|
|
1637
|
+
}
|
|
1638
|
+
const dependencies = await extractPackageDependencies(logger, rootDir);
|
|
1639
|
+
if (!await frameworkPluginFactory.isCompatible(dependencies)) {
|
|
1640
|
+
throw new Error(
|
|
1641
|
+
`Preview.js \u7684 framework plugin ${frameworkPluginFactory.info.name} \u4E0E\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u4F9D\u8D56\u4E0D\u517C\u5BB9\u3002`
|
|
1642
|
+
);
|
|
1643
|
+
}
|
|
1644
|
+
logger.debug(
|
|
1645
|
+
`\u4F7F\u7528 ${frameworkPluginFactory.info.name} \u5728\u76EE\u5F55: ${rootDir} \u4E2D\u521B\u5EFA\u5DE5\u4F5C\u533A`
|
|
1646
|
+
);
|
|
1647
|
+
const frameworkPlugin = await frameworkPluginFactory.create({
|
|
1648
|
+
rootDir,
|
|
1649
|
+
reader,
|
|
1650
|
+
logger,
|
|
1651
|
+
dependencies
|
|
1652
|
+
});
|
|
1653
|
+
const activePreviewers = /* @__PURE__ */ new Set();
|
|
1654
|
+
const workspace = {
|
|
1655
|
+
frameworkPluginName: frameworkPluginFactory.info.name,
|
|
1656
|
+
crawlFiles: frameworkPlugin.crawlFiles,
|
|
1657
|
+
typeAnalyzer: frameworkPlugin.typeAnalyzer,
|
|
1658
|
+
rootDir,
|
|
1659
|
+
reader,
|
|
1660
|
+
// 启动预览服务器
|
|
1661
|
+
startServer: async ({
|
|
1662
|
+
asMiddleware,
|
|
1663
|
+
port: maybePort,
|
|
1664
|
+
clientPort,
|
|
1665
|
+
onStop
|
|
1666
|
+
} = {}) => {
|
|
1667
|
+
const port = maybePort || await getFreePort(3140);
|
|
1668
|
+
const router = new ApiRouter(logger);
|
|
1669
|
+
router.registerRPC(RPCs.Analyze, async ({ previewableIds }) => {
|
|
1670
|
+
logger.debug(`\u5206\u6790: ${previewableIds.join(", ")}`);
|
|
1671
|
+
const detected = await frameworkPlugin.crawlFiles([
|
|
1672
|
+
...new Set(
|
|
1673
|
+
previewableIds.map(
|
|
1674
|
+
(c) => path.join(rootDir, decodePreviewableId(c).filePath)
|
|
1675
|
+
)
|
|
1676
|
+
)
|
|
1677
|
+
]);
|
|
1678
|
+
logger.debug(
|
|
1679
|
+
`\u68C0\u6D4B\u5230 ${detected.components.length} \u4E2A\u7EC4\u4EF6\u548C ${detected.stories.length} \u4E2Astory`
|
|
1680
|
+
);
|
|
1681
|
+
const previewables = [];
|
|
1682
|
+
const idToDetectedComponent = Object.fromEntries(
|
|
1683
|
+
detected.components.map((c) => [c.id, c])
|
|
1684
|
+
);
|
|
1685
|
+
const idToDetectedStory = Object.fromEntries(
|
|
1686
|
+
detected.stories.map((c) => [c.id, c])
|
|
1687
|
+
);
|
|
1688
|
+
let types = {};
|
|
1689
|
+
for (const id of previewableIds) {
|
|
1690
|
+
const component = idToDetectedComponent[id];
|
|
1691
|
+
const story = idToDetectedStory[id];
|
|
1692
|
+
let componentTypes;
|
|
1693
|
+
if (component) {
|
|
1694
|
+
logger.debug(`\u5206\u6790\u7EC4\u4EF6: ${id}`);
|
|
1695
|
+
let props;
|
|
1696
|
+
({ props, types: componentTypes } = await component.analyze());
|
|
1697
|
+
logger.debug(`\u5B8C\u6210\u7EC4\u4EF6: ${id} \u5206\u6790`);
|
|
1698
|
+
previewables.push({
|
|
1699
|
+
kind: "component",
|
|
1700
|
+
id,
|
|
1701
|
+
exported: component.exported,
|
|
1702
|
+
sourcePosition: component.sourcePosition,
|
|
1703
|
+
props
|
|
1704
|
+
});
|
|
1705
|
+
} else if (story) {
|
|
1706
|
+
let props;
|
|
1707
|
+
if (story.associatedComponent) {
|
|
1708
|
+
logger.debug(`\u5206\u6790 story: ${id}`);
|
|
1709
|
+
({ props, types: componentTypes } = await story.associatedComponent.analyze());
|
|
1710
|
+
logger.debug(`\u5B8C\u6210 story: ${id} \u5206\u6790`);
|
|
1711
|
+
} else {
|
|
1712
|
+
logger.debug(`story: ${id} \u6CA1\u6709\u5173\u8054\u7684\u7EC4\u4EF6`);
|
|
1713
|
+
props = UNKNOWN_TYPE;
|
|
1714
|
+
componentTypes = {};
|
|
1715
|
+
}
|
|
1716
|
+
previewables.push({
|
|
1717
|
+
kind: "story",
|
|
1718
|
+
id,
|
|
1719
|
+
sourcePosition: story.sourcePosition,
|
|
1720
|
+
associatedComponentId: story.associatedComponent?.id || null,
|
|
1721
|
+
props,
|
|
1722
|
+
args: (await story.analyze()).args
|
|
1723
|
+
});
|
|
1724
|
+
} else {
|
|
1725
|
+
const { filePath, name } = decodePreviewableId(id);
|
|
1726
|
+
throw new Error(`\u5728 ${filePath} \u4E2D\u672A\u627E\u5230\u7EC4\u4EF6 ${name}. `);
|
|
1727
|
+
}
|
|
1728
|
+
types = { ...types, ...componentTypes };
|
|
1729
|
+
}
|
|
1730
|
+
return {
|
|
1731
|
+
previewables,
|
|
1732
|
+
types
|
|
1733
|
+
};
|
|
1734
|
+
});
|
|
1735
|
+
router.registerRPC(RPCs.GetInfo, async () => ({
|
|
1736
|
+
frameworkPlugin: frameworkPluginFactory.info
|
|
1737
|
+
}));
|
|
1738
|
+
router.registerRPC(
|
|
1739
|
+
RPCs.CrawlFiles,
|
|
1740
|
+
(options) => crawlFiles(logger, workspace, frameworkPlugin, options)
|
|
1741
|
+
);
|
|
1742
|
+
const middlewares = [
|
|
1743
|
+
// 0. 增加cors能力
|
|
1744
|
+
cors(),
|
|
1745
|
+
// 1. 处理 JSON 请求
|
|
1746
|
+
express.json(),
|
|
1747
|
+
// 2. 处理 URL 编码的请求
|
|
1748
|
+
async (req, res, next) => {
|
|
1749
|
+
if (req.path.startsWith("/api/")) {
|
|
1750
|
+
res.json(await router.handle(req.path.substr(5), req.body));
|
|
1751
|
+
} else {
|
|
1752
|
+
next();
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
];
|
|
1756
|
+
if (onServerStart) {
|
|
1757
|
+
const { middlewares: additionalMiddlewares = [] } = await onServerStart(
|
|
1758
|
+
{
|
|
1759
|
+
registerRPC: (endpoint, handler) => router.registerRPC(endpoint, handler),
|
|
1760
|
+
workspace
|
|
1761
|
+
}
|
|
1762
|
+
);
|
|
1763
|
+
middlewares.push(...additionalMiddlewares);
|
|
1764
|
+
}
|
|
1765
|
+
const getHttpServer = asMiddleware ? async (router2) => {
|
|
1766
|
+
const unregister = asMiddleware.register(router2);
|
|
1767
|
+
return {
|
|
1768
|
+
server: asMiddleware.server,
|
|
1769
|
+
disposeHttpServer: async () => {
|
|
1770
|
+
unregister();
|
|
1771
|
+
}
|
|
1772
|
+
};
|
|
1773
|
+
} : async (router2) => {
|
|
1774
|
+
logger.debug("\u542F\u52A8 Express \u670D\u52A1\u5668");
|
|
1775
|
+
const app = express();
|
|
1776
|
+
app.use(router2);
|
|
1777
|
+
const server = await new Promise((resolve) => {
|
|
1778
|
+
const server2 = app.listen(port, () => {
|
|
1779
|
+
logger.info(
|
|
1780
|
+
`Preview.js \u9884\u89C8\u670D\u52A1\u8FD0\u884C\u5728 http://localhost:${port}.`
|
|
1781
|
+
);
|
|
1782
|
+
resolve(server2);
|
|
1783
|
+
});
|
|
1784
|
+
});
|
|
1785
|
+
const serverTerminator = createHttpTerminator({
|
|
1786
|
+
server,
|
|
1787
|
+
gracefulTerminationTimeout: 0
|
|
1788
|
+
});
|
|
1789
|
+
return {
|
|
1790
|
+
server,
|
|
1791
|
+
disposeHttpServer: async () => {
|
|
1792
|
+
await serverTerminator.terminate();
|
|
1793
|
+
logger.info("Preview.js \u9884\u89C8\u670D\u52A1\u5668\u5DF2\u505C\u6B62.");
|
|
1794
|
+
}
|
|
1795
|
+
};
|
|
1796
|
+
};
|
|
1797
|
+
const previewer = new Previewer({
|
|
1798
|
+
reader,
|
|
1799
|
+
rootDir,
|
|
1800
|
+
// TODO: Use a cleaner approach.
|
|
1801
|
+
previewDirPath: path.join(
|
|
1802
|
+
path.dirname(path.dirname(require.resolve("@cfp-studio/iframe"))),
|
|
1803
|
+
"preview"
|
|
1804
|
+
),
|
|
1805
|
+
frameworkPlugin,
|
|
1806
|
+
logger,
|
|
1807
|
+
middlewares,
|
|
1808
|
+
getHttpServer,
|
|
1809
|
+
port,
|
|
1810
|
+
clientPort
|
|
1811
|
+
});
|
|
1812
|
+
await previewer.start();
|
|
1813
|
+
activePreviewers.add(previewer);
|
|
1814
|
+
return {
|
|
1815
|
+
port,
|
|
1816
|
+
// 服务器端口号
|
|
1817
|
+
stop: async () => {
|
|
1818
|
+
activePreviewers.delete(previewer);
|
|
1819
|
+
await previewer.stop();
|
|
1820
|
+
await onStop?.();
|
|
1821
|
+
}
|
|
1822
|
+
};
|
|
1823
|
+
},
|
|
1824
|
+
// 清理工作区资源
|
|
1825
|
+
dispose: async () => {
|
|
1826
|
+
await Promise.all(
|
|
1827
|
+
[...activePreviewers].map((previewer) => previewer.stop())
|
|
1828
|
+
);
|
|
1829
|
+
activePreviewers.clear();
|
|
1830
|
+
frameworkPlugin.dispose();
|
|
1831
|
+
}
|
|
1832
|
+
};
|
|
1833
|
+
return workspace;
|
|
1834
|
+
}
|
|
1835
|
+
function findWorkspaceRoot(absoluteFilePath) {
|
|
1836
|
+
let dirPath = path.resolve(absoluteFilePath);
|
|
1837
|
+
while (dirPath !== path.dirname(dirPath)) {
|
|
1838
|
+
if (fs$1.existsSync(path.join(dirPath, "package.json"))) {
|
|
1839
|
+
return dirPath;
|
|
1840
|
+
}
|
|
1841
|
+
dirPath = path.dirname(dirPath);
|
|
1842
|
+
}
|
|
1843
|
+
return null;
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
export { createWorkspace, findCompatiblePlugin, findWorkspaceRoot, toVitePath };
|