@cfp-studio/core 1.0.3 → 1.0.6

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Zenc Labs Pty Ltd
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Zenc Labs Pty Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,75 +1,75 @@
1
- # @cfp-studio/core
2
-
3
- CFP Studio 的核心运行时与服务编排包,负责组件/Story 静态分析、预览服务、插件架构、Vite 集成、API 路由、依赖管理等。是整个 monorepo 的中枢和 glue 层。
4
-
5
- ---
6
-
7
- ## 架构与工作原理
8
-
9
- ### 1. 预览服务与中间件
10
- - 启动 Express/Vite 组合服务,自动托管前端产物与 API。
11
- - 支持自定义中间件(如 inspector、静态资源、CORS、API 路由等)。
12
- - 通过 `Previewer` 类统一管理服务生命周期、端口、热重载、缓存等。
13
-
14
- ### 2. 插件化框架支持
15
- - 通过 `FrameworkPluginFactory`/`FrameworkPlugin` 接口,支持多框架(React/Vue/Svelte/Solid/Preact 等)插件热插拔。
16
- - 插件可自定义类型分析、依赖检测、Vite 配置、特殊文件处理等。
17
- - 自动检测项目依赖,动态选择兼容插件。
18
-
19
- ### 3. 组件/Story 静态分析
20
- - 集成 `@cfp-studio/analyzer-api`,支持 TS/JSX 组件、Story、属性、类型、propTypes 等静态分析。
21
- - 支持批量文件爬取、缓存、依赖追踪、增量分析。
22
- - 统一可预览 ID 生成与解析,便于前后端通信。
23
-
24
- ### 4. Vite 深度集成与虚拟文件
25
- - 内置多种 Vite 插件(如虚拟文件、CSS modules、inspector、public asset import、local eval 等)。
26
- - 支持虚拟文件系统(VFS),可动态生成/注入模块。
27
- - 自动处理 alias、tsconfig 路径、全局样式、热重载等。
28
-
29
- ### 5. API 路由与远程调用
30
- - 内置 `ApiRouter`,支持类型安全的 RPC 路由与分发。
31
- - 支持插件/服务注册自定义 RPC 端点。
32
- - 统一错误处理与日志。
33
-
34
- ### 6. 缓存与依赖管理
35
- - 自动管理缓存目录,支持多版本隔离。
36
- - 支持依赖包版本检测、动态加载、兼容性校验。
37
-
38
- ---
39
-
40
- ## 主要 API/模块
41
- - `Previewer`:预览服务主类
42
- - `FrameworkPluginFactory`/`FrameworkPlugin`:插件接口
43
- - `crawlFiles`/`findFiles`:批量文件爬取与查找
44
- - `ApiRouter`:RPC 路由
45
- - `ViteManager`:Vite 服务与插件集成
46
- - `getCacheDir`:缓存目录管理
47
- - `extractPackageDependencies`:依赖检测
48
- - `toVitePath`:路径工具
49
-
50
- ## 用法示例
51
-
52
- ```ts
53
- import { Previewer, findCompatiblePlugin } from '@cfp-studio/core';
54
- const plugin = await findCompatiblePlugin({ rootDir: '/project' });
55
- const previewer = new Previewer({
56
- rootDir: '/project',
57
- frameworkPlugin: plugin,
58
- // ...其他参数
59
- });
60
- await previewer.start();
61
- ```
62
-
63
- ## 依赖
64
- - `@cfp-studio/analyzer-api`、`@cfp-studio/api`、`@cfp-studio/config`、`@cfp-studio/iframe`、`@cfp-studio/middleware`、`@cfp-studio/serializable-values`、`@cfp-studio/type-analyzer`、`@cfp-studio/vfs`
65
- - `express`、`vite`、`pino`、`fs-extra`、`axios`、`zod` 等
66
-
67
- ## 构建
68
-
69
- ```sh
70
- pnpm build
71
- ```
72
-
73
- ## 许可证
74
-
75
- MIT
1
+ # @cfp-studio/core
2
+
3
+ CFP Studio 的核心运行时与服务编排包,负责组件/Story 静态分析、预览服务、插件架构、Vite 集成、API 路由、依赖管理等。是整个 monorepo 的中枢和 glue 层。
4
+
5
+ ---
6
+
7
+ ## 架构与工作原理
8
+
9
+ ### 1. 预览服务与中间件
10
+ - 启动 Express/Vite 组合服务,自动托管前端产物与 API。
11
+ - 支持自定义中间件(如 inspector、静态资源、CORS、API 路由等)。
12
+ - 通过 `Previewer` 类统一管理服务生命周期、端口、热重载、缓存等。
13
+
14
+ ### 2. 插件化框架支持
15
+ - 通过 `FrameworkPluginFactory`/`FrameworkPlugin` 接口,支持多框架(React/Vue/Svelte/Solid/Preact 等)插件热插拔。
16
+ - 插件可自定义类型分析、依赖检测、Vite 配置、特殊文件处理等。
17
+ - 自动检测项目依赖,动态选择兼容插件。
18
+
19
+ ### 3. 组件/Story 静态分析
20
+ - 集成 `@cfp-studio/analyzer-api`,支持 TS/JSX 组件、Story、属性、类型、propTypes 等静态分析。
21
+ - 支持批量文件爬取、缓存、依赖追踪、增量分析。
22
+ - 统一可预览 ID 生成与解析,便于前后端通信。
23
+
24
+ ### 4. Vite 深度集成与虚拟文件
25
+ - 内置多种 Vite 插件(如虚拟文件、CSS modules、inspector、public asset import、local eval 等)。
26
+ - 支持虚拟文件系统(VFS),可动态生成/注入模块。
27
+ - 自动处理 alias、tsconfig 路径、全局样式、热重载等。
28
+
29
+ ### 5. API 路由与远程调用
30
+ - 内置 `ApiRouter`,支持类型安全的 RPC 路由与分发。
31
+ - 支持插件/服务注册自定义 RPC 端点。
32
+ - 统一错误处理与日志。
33
+
34
+ ### 6. 缓存与依赖管理
35
+ - 自动管理缓存目录,支持多版本隔离。
36
+ - 支持依赖包版本检测、动态加载、兼容性校验。
37
+
38
+ ---
39
+
40
+ ## 主要 API/模块
41
+ - `Previewer`:预览服务主类
42
+ - `FrameworkPluginFactory`/`FrameworkPlugin`:插件接口
43
+ - `crawlFiles`/`findFiles`:批量文件爬取与查找
44
+ - `ApiRouter`:RPC 路由
45
+ - `ViteManager`:Vite 服务与插件集成
46
+ - `getCacheDir`:缓存目录管理
47
+ - `extractPackageDependencies`:依赖检测
48
+ - `toVitePath`:路径工具
49
+
50
+ ## 用法示例
51
+
52
+ ```ts
53
+ import { Previewer, findCompatiblePlugin } from '@cfp-studio/core';
54
+ const plugin = await findCompatiblePlugin({ rootDir: '/project' });
55
+ const previewer = new Previewer({
56
+ rootDir: '/project',
57
+ frameworkPlugin: plugin,
58
+ // ...其他参数
59
+ });
60
+ await previewer.start();
61
+ ```
62
+
63
+ ## 依赖
64
+ - `@cfp-studio/analyzer-api`、`@cfp-studio/api`、`@cfp-studio/fiber-reader`、`@cfp-studio/iframe`、`@cfp-studio/type-analyzer`、`@cfp-studio/vfs`
65
+ - `express`、`vite`、`pino`、`fs-extra`、`axios`、`zod` 等
66
+
67
+ ## 构建
68
+
69
+ ```sh
70
+ pnpm build
71
+ ```
72
+
73
+ ## 许可证
74
+
75
+ MIT
package/dist/index.d.mts CHANGED
@@ -1,13 +1,14 @@
1
- import { Analyzer } from '@cfp-studio/analyzer-api';
2
- import { TypeAnalyzer } from '@cfp-studio/type-analyzer';
3
- import { Reader } from '@cfp-studio/vfs';
4
- import * as express from 'express';
5
- import express__default from 'express';
6
- import http from 'node:http';
7
- import { Logger } from 'pino';
8
- import { FrameworkPluginInfo, RPC, RequestOf, ResponseOf } from '@cfp-studio/api';
9
- import * as vite from 'vite';
1
+ import { Analyzer } from "@cfp-studio/analyzer-api";
2
+ import { FrameworkPluginInfo, RPC, RequestOf, ResponseOf } from "@cfp-studio/api";
3
+ import { TypeAnalyzer } from "@cfp-studio/type-analyzer";
4
+ import { Reader } from "@cfp-studio/vfs";
5
+ import * as express$1 from "express";
6
+ import express from "express";
7
+ import { Logger } from "pino";
8
+ import * as vite from "vite";
9
+ import http from "node:http";
10
10
 
11
+ //#region src/plugins/dependencies.d.ts
11
12
  /**
12
13
  * 定义包依赖项的类型,它是一个记录类型,键为包名,值为包含主要版本号和读取已安装版本方法的对象
13
14
  * @typedef {Object} PackageDependencies
@@ -15,75 +16,76 @@ import * as vite from 'vite';
15
16
  * @property {function} readInstalledVersion - 异步读取已安装包版本的函数,返回一个 Promise,解析为字符串或 null
16
17
  */
17
18
  type PackageDependencies = Record<string, {
18
- /** @deprecated */
19
- majorVersion: number;
20
- /**
21
- * 异步读取已安装包的版本号
22
- * @returns {Promise<string | null>} - 一个 Promise,解析为已安装包的版本号字符串,如果读取失败则为 null
23
- */
24
- readInstalledVersion(): Promise<string | null>;
19
+ /** @deprecated */majorVersion: number;
20
+ /**
21
+ * 异步读取已安装包的版本号
22
+ * @returns {Promise<string | null>} - 一个 Promise,解析为已安装包的版本号字符串,如果读取失败则为 null
23
+ */
24
+ readInstalledVersion(): Promise<string | null>;
25
25
  }>;
26
-
26
+ //#endregion
27
+ //#region src/plugins/framework.d.ts
27
28
  /**
28
29
  * 定义框架插件工厂的接口。
29
30
  * 该工厂用于创建框架插件实例,并提供检查兼容性的方法。
30
31
  */
31
32
  interface FrameworkPluginFactory {
32
- /**
33
- * 框架插件的信息,包含插件的基本描述和元数据。
34
- */
35
- info: FrameworkPluginInfo;
36
- /**
37
- * 检查当前项目的依赖是否与该框架插件兼容。
38
- *
39
- * @param dependencies - 项目的依赖包信息。
40
- * @returns 一个 Promise,解析为布尔值,表示是否兼容。
41
- */
42
- isCompatible(dependencies: PackageDependencies): Promise<boolean>;
43
- /**
44
- * 创建框架插件实例。
45
- *
46
- * @param options - 创建插件所需的选项。
47
- * @param options.rootDir - 项目的根目录。
48
- * @param options.reader - 用于读取文件的读取器。
49
- * @param options.logger - 日志记录器,用于记录插件运行时的信息。
50
- * @param options.dependencies - 项目的依赖包信息。
51
- * @returns 一个 Promise,解析为创建的框架插件实例。
52
- */
53
- create(options: {
54
- rootDir: string;
55
- reader: Reader;
56
- logger: Logger;
57
- dependencies: PackageDependencies;
58
- }): Promise<FrameworkPlugin>;
33
+ /**
34
+ * 框架插件的信息,包含插件的基本描述和元数据。
35
+ */
36
+ info: FrameworkPluginInfo;
37
+ /**
38
+ * 检查当前项目的依赖是否与该框架插件兼容。
39
+ *
40
+ * @param dependencies - 项目的依赖包信息。
41
+ * @returns 一个 Promise,解析为布尔值,表示是否兼容。
42
+ */
43
+ isCompatible(dependencies: PackageDependencies): Promise<boolean>;
44
+ /**
45
+ * 创建框架插件实例。
46
+ *
47
+ * @param options - 创建插件所需的选项。
48
+ * @param options.rootDir - 项目的根目录。
49
+ * @param options.reader - 用于读取文件的读取器。
50
+ * @param options.logger - 日志记录器,用于记录插件运行时的信息。
51
+ * @param options.dependencies - 项目的依赖包信息。
52
+ * @returns 一个 Promise,解析为创建的框架插件实例。
53
+ */
54
+ create(options: {
55
+ rootDir: string;
56
+ reader: Reader;
57
+ logger: Logger;
58
+ dependencies: PackageDependencies;
59
+ }): Promise<FrameworkPlugin>;
59
60
  }
60
61
  /**
61
62
  * 定义框架插件的接口。
62
63
  * 该插件继承自 Analyzer 接口,并提供了一些额外的配置和方法。
63
64
  */
64
65
  interface FrameworkPlugin extends Analyzer {
65
- /**
66
- * 默认包装器的文件路径。
67
- */
68
- defaultWrapperPath: string;
69
- /**
70
- * 预览目录的文件路径。
71
- */
72
- previewDirPath: string;
73
- /**
74
- * 生成 Vite 配置的函数。
75
- *
76
- * @param configuredPlugins - 已配置的 Vite 插件列表。
77
- * @returns Vite 用户配置对象。
78
- */
79
- viteConfig: (configuredPlugins: vite.Plugin[]) => vite.UserConfig;
80
- /**
81
- * 清理插件资源的方法。
82
- * 当插件不再使用时,调用此方法释放资源。
83
- */
84
- dispose(): void;
66
+ /**
67
+ * 默认包装器的文件路径。
68
+ */
69
+ defaultWrapperPath: string;
70
+ /**
71
+ * 预览目录的文件路径。
72
+ */
73
+ previewDirPath: string;
74
+ /**
75
+ * 生成 Vite 配置的函数。
76
+ *
77
+ * @param configuredPlugins - 已配置的 Vite 插件列表。
78
+ * @returns Vite 用户配置对象。
79
+ */
80
+ viteConfig: (configuredPlugins: vite.Plugin[]) => vite.UserConfig;
81
+ /**
82
+ * 清理插件资源的方法。
83
+ * 当插件不再使用时,调用此方法释放资源。
84
+ */
85
+ dispose(): void;
85
86
  }
86
-
87
+ //#endregion
88
+ //#region src/router.d.ts
87
89
  /**
88
90
  * 定义注册 RPC 端点的函数类型。
89
91
  * @template E - RPC 端点的类型。
@@ -99,7 +101,8 @@ type RegisterRPC = <E extends RPC<any, any>>(endpoint: E, handler: RequestHandle
99
101
  * @returns 包含响应结果的 Promise。
100
102
  */
101
103
  type RequestHandler<Req, Res> = (request: Req) => Promise<Res>;
102
-
104
+ //#endregion
105
+ //#region src/preview-env.d.ts
103
106
  /**
104
107
  * 定义 OnServerStart 类型,这是一个异步函数类型,用于在服务器启动时执行特定操作
105
108
  * @param options - 包含服务器启动所需的选项
@@ -109,25 +112,26 @@ type RequestHandler<Req, Res> = (request: Req) => Promise<Res>;
109
112
  * @returns 返回一个 Promise,该 Promise 解析为一个包含中间件数组的对象
110
113
  */
111
114
  type OnServerStart = (options: {
112
- /**
113
- * 可选的版本代码
114
- */
115
- versionCode?: string;
116
- /**
117
- * 用于注册远程过程调用的函数
118
- */
119
- registerRPC: RegisterRPC;
120
- /**
121
- * 当前的工作区对象
122
- */
123
- workspace: Workspace;
115
+ /**
116
+ * 可选的版本代码
117
+ */
118
+ versionCode?: string;
119
+ /**
120
+ * 用于注册远程过程调用的函数
121
+ */
122
+ registerRPC: RegisterRPC;
123
+ /**
124
+ * 当前的工作区对象
125
+ */
126
+ workspace: Workspace;
124
127
  }) => Promise<{
125
- /**
126
- * 可选的 express 请求处理中间件数组
127
- */
128
- middlewares?: express.RequestHandler[];
128
+ /**
129
+ * 可选的 express 请求处理中间件数组
130
+ */
131
+ middlewares?: express$1.RequestHandler[];
129
132
  }>;
130
-
133
+ //#endregion
134
+ //#region src/plugins/find-compatible-plugin.d.ts
131
135
  /**
132
136
  * 查找与项目依赖兼容的框架插件
133
137
  * @param logger - 用于日志记录的 Logger 实例
@@ -136,9 +140,11 @@ type OnServerStart = (options: {
136
140
  * @returns 兼容插件的名称,如果未找到则返回 null
137
141
  */
138
142
  declare function findCompatiblePlugin(logger: Logger, rootDir: string, frameworkPlugins: FrameworkPluginFactory[]): Promise<string>;
139
-
143
+ //#endregion
144
+ //#region src/vite/vite-paths.d.ts
140
145
  declare function toVitePath(absoluteFilePath: string): string;
141
-
146
+ //#endregion
147
+ //#region src/index.d.ts
142
148
  /**
143
149
  * 创建一个新的工作区实例。
144
150
  *
@@ -152,12 +158,18 @@ declare function toVitePath(absoluteFilePath: string): string;
152
158
  * @param options.onServerStart 服务器启动时的回调函数
153
159
  * @returns Workspace 返回一个工作区实例
154
160
  */
155
- declare function createWorkspace({ rootDir, frameworkPlugin: frameworkPluginFactory, logger, reader, onServerStart, }: {
156
- rootDir: string;
157
- frameworkPlugin: FrameworkPluginFactory;
158
- logger?: Logger;
159
- reader?: Reader;
160
- onServerStart?: OnServerStart;
161
+ declare function createWorkspace({
162
+ rootDir,
163
+ frameworkPlugin: frameworkPluginFactory,
164
+ logger,
165
+ reader,
166
+ onServerStart
167
+ }: {
168
+ rootDir: string;
169
+ frameworkPlugin: FrameworkPluginFactory;
170
+ logger?: Logger;
171
+ reader?: Reader;
172
+ onServerStart?: OnServerStart;
161
173
  }): Promise<Workspace>;
162
174
  /**
163
175
  * 查找包含 package.json 的最近祖先目录路径。
@@ -182,25 +194,25 @@ declare function findWorkspaceRoot(absoluteFilePath: string): string | null;
182
194
  * @property dispose 清理工作区资源函数
183
195
  */
184
196
  interface Workspace {
185
- rootDir: string;
186
- reader: Reader;
187
- frameworkPluginName: string;
188
- typeAnalyzer: Omit<TypeAnalyzer, "dispose">;
189
- crawlFiles: Analyzer["crawlFiles"];
190
- startServer: (options?: {
191
- port?: number;
192
- clientPort?: number;
193
- onStop?: () => void;
194
- } & ({
195
- asMiddleware?: never;
196
- } | {
197
- asMiddleware: {
198
- server: http.Server;
199
- register: (handler: express__default.RequestHandler) => () => void;
200
- };
201
- port: number;
202
- })) => Promise<PreviewServer>;
203
- dispose(): Promise<void>;
197
+ rootDir: string;
198
+ reader: Reader;
199
+ frameworkPluginName: string;
200
+ typeAnalyzer: Omit<TypeAnalyzer, "dispose">;
201
+ crawlFiles: Analyzer["crawlFiles"];
202
+ startServer: (options?: {
203
+ port?: number;
204
+ clientPort?: number;
205
+ onStop?: () => void;
206
+ } & ({
207
+ asMiddleware?: never;
208
+ } | {
209
+ asMiddleware: {
210
+ server: http.Server;
211
+ register: (handler: express.RequestHandler) => () => void;
212
+ };
213
+ port: number;
214
+ })) => Promise<PreviewServer>;
215
+ dispose(): Promise<void>;
204
216
  }
205
217
  /**
206
218
  * 预览服务器接口定义。
@@ -211,8 +223,8 @@ interface Workspace {
211
223
  * @property stop 停止预览服务器函数
212
224
  */
213
225
  interface PreviewServer {
214
- port: number;
215
- stop(): Promise<void>;
226
+ port: number;
227
+ stop(): Promise<void>;
216
228
  }
217
-
218
- export { type FrameworkPlugin, type FrameworkPluginFactory, type OnServerStart, type PackageDependencies, type PreviewServer, type Workspace, createWorkspace, findCompatiblePlugin, findWorkspaceRoot, toVitePath };
229
+ //#endregion
230
+ export { type FrameworkPlugin, type FrameworkPluginFactory, type OnServerStart, type PackageDependencies, PreviewServer, Workspace, createWorkspace, findCompatiblePlugin, findWorkspaceRoot, toVitePath };
package/dist/index.mjs CHANGED
@@ -1,9 +1,7 @@
1
- import{decodePreviewableId as O}from"@cfp-studio/analyzer-api";import{RPCs as G}from"@cfp-studio/api";import{UNKNOWN_TYPE as fe}from"@cfp-studio/type-analyzer";import{createStackedReader as he,createFileSystemReader as z}from"@cfp-studio/vfs";import R from"express";import me from"cors";import w from"fs-extra";import{createHttpTerminator as ge}from"http-terminator";import{createRequire as Z}from"node:module";import a from"node:path";import we from"pino";import ve from"pino-pretty";import{exclusivePromiseRunner as ee}from"exclusive-promises";import Ee from"node:fs";import Fe from"node:url";import{globby as ye}from"globby";import Ce from"node:net";import{assertNever as De}from"assert-never";import be from"axios";import Pe from"@fwouts/vite-tsconfig-paths";import{PREVIEW_CONFIG_NAMES as je,readConfig as $e}from"@cfp-studio/config";import ke from"rollup-plugin-friendly-type-imports";import{loadTsconfig as Se}from"tsconfig-paths/lib/tsconfig-loader.js";import*as q from"vite";import{transformWithEsbuild as Ae,searchForWorkspaceRoot as _e}from"vite";import{z as A}from"zod";import{escape as Be}from"html-escaper";import{launchEditorMiddleware as xe}from"@cfp-studio/middleware";function te(r){try{const e=Fe.fileURLToPath(new URL(".",import.meta.url)),{version:t}=JSON.parse(Ee.readFileSync(a.resolve(e,"..","package.json"),"utf8"));return a.resolve(r,"node_modules",".previewjs",`v${t}`)}catch(e){throw new Error(`\u65E0\u6CD5\u83B7\u53D6 @cfp-studio/core \u7684\u7248\u672C\u53F7.
2
- ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+a.sep:"",n=await ye(s+e,{gitignore:!0,ignore:["**/node_modules/**"],cwd:o,absolute:!0,followSymbolicLinks:!1,suppressErrors:!0,deep:t.maxDepth});let u=r.replace(/\\/g,"/");return u.endsWith("/")||(u+="/"),n.filter(l=>l.startsWith(u)).sort()}async function ie(r,e=r){try{if(await w.exists(a.join(r,".git")))return r;const t=a.dirname(r);return!t||t===r?e:ie(t,e)}catch{return e}}const se=new Set(["jsconfig.json","tsconfig.json","package.json","package-lock.json","pnpm-lock.yaml","yarn.lock"]),Me=ee();function Oe(r,e,t,o={}){return Me(async()=>{r.debug(`\u5F00\u59CB\u626B\u63CF\u7EC4\u4EF6\uFF0C\u626B\u63CF\u53C2\u6570: ${JSON.stringify(o)}`);const i=Date.now(),s=a.join(te(e.rootDir),"components.json"),n=await(async()=>{if(o.filePaths)return o.filePaths.map(h=>a.join(e.rootDir,h));r.debug(`\u626B\u63CF\u76EE\u5F55: ${e.rootDir}\uFF0C\u91C7\u96C6\u53EF\u626B\u63CF\u6587\u4EF6`);const c=await re(e.rootDir,"**/*.@(js|jsx|ts|tsx|svelte|vue)");return r.debug(`\u627E\u5230 ${c.length} \u4E2A\u5305\u542B\u7EC4\u4EF6\u7684\u6587\u4EF6`),c})(),u=new Set(n.map(c=>a.relative(e.rootDir,c).replace(/\\/g,"/")));let l={detectionStartTimestamp:0,components:[],stories:[]};if(w.existsSync(s))try{l=JSON.parse(w.readFileSync(s,"utf8"))}catch{r.warn(`\u65E0\u6CD5\u8F6C\u6362 ${s} \u4E2D\u5B58\u50A8\u7684\u7F13\u5B58\u4FE1\u606F`)}l.detectionStartTimestamp<await We(e.rootDir)&&(l={detectionStartTimestamp:0,components:[],stories:[]});const p=n.filter(c=>{const h=e.reader.readSync(c);return h?.kind==="file"&&(o.forceRefresh||h.lastModifiedMillis()>=l.detectionStartTimestamp)}),d=new Set(p.map(c=>a.relative(e.rootDir,c).replace(/\\/g,"/"))),f=({id:c})=>{const h=O(c).filePath;return u.has(h)&&!d.has(h)},g=l.components.filter(f),m=l.stories.filter(f),{components:y,stories:D}=await Re(r,e,t,p),v=[...g,...y],E=[...m,...D];if(!o.filePaths){await w.mkdirp(a.dirname(s));const c={detectionStartTimestamp:i,components:v,stories:E};await w.writeFile(s,JSON.stringify(c))}return{components:v,stories:E}})}async function Re(r,e,t,o){const i=[],s=[];if(o.length===0)return{components:i,stories:s};r.debug(`\u5728\u4E0B\u8FF0\u6587\u4EF6\u4E2D\u67E5\u627E\u7EC4\u4EF6:
3
- - ${o.map(u=>a.relative(e.rootDir,u)).join(`
4
- - `)}`);const n=await t.crawlFiles(o);r.debug("\u7EC4\u4EF6\u68C0\u6D4B\u5B8C\u6210");for(const u of n.components)i.push({id:u.id,sourcePosition:u.sourcePosition,exported:u.exported});for(const u of n.stories)s.push({id:u.id,sourcePosition:u.sourcePosition,associatedComponentId:u.associatedComponent?.id||null});return{components:i,stories:s}}async function We(r){const e=a.join(r,"node_modules");let t=0;if(await w.pathExists(e))for(const o of await w.readdir(e)){const i=a.join(e,o),s=await w.lstat(i);(s.isDirectory()||s.isSymbolicLink())&&(t=Math.max(t,s.mtimeMs))}for(const o of se){const i=a.join(r,o);if(await w.pathExists(i)){const s=await w.stat(i);t=Math.max(t,s.mtimeMs)}}return t}async function Ne(r){for(let e=r;;e++)if(await Ie(e))return e}async function Ie(r){return new Promise(e=>{const t=Ce.createServer();t.unref(),t.on("error",()=>e(!1)),t.listen(r,()=>{t.close(()=>{e(!0)})})})}const Te=Z(import.meta.url);async function oe(r,e){const t=a.join(e,"package.json");if(!await w.pathExists(t))return{};const{dependencies:o,devDependencies:i,peerDependencies:s}=JSON.parse(await w.readFile(t,"utf8")),n={...o,...i,...s},u=new Map;for(const[l,p]of Object.entries(n)){let d=0;typeof p=="string"&&(p.startsWith("^")||p.startsWith("~")?d=Number.parseInt(p.slice(1)):d=Number.parseInt(p));const f=async()=>{try{const g=He(l,e);let m=g;for(;m!==a.dirname(m);){const y=a.join(m,"package.json");if(w.existsSync(y)){const D=JSON.parse(await w.readFile(y,"utf8"));if(typeof D.version=="string")return D.version;throw new Error(`\u5305: ${y} \u7684\u7248\u672C\u53F7\u5F02\u5E38`)}m=a.dirname(m)}throw new Error(`\u6839\u636E\u6A21\u5757: ${g} \u7684\u5165\u53E3\u8DEF\u5F84\u65E0\u6CD5\u627E\u5230 package.json`)}catch(g){return r.error(g,`\u65E0\u6CD5\u8BFB\u53D6\u5305: ${l} \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`),null}};u.set(l,{majorVersion:d,readInstalledVersion:f})}return Object.fromEntries(u)}function He(r,e){try{return Te.resolve(r,{paths:[e]})}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ERR_PACKAGE_PATH_NOT_EXPORTED"){const o=t.message.match(/No "exports" main defined in (.*)(\/|\\)package\.json/);if(o)return o[1]??""}throw t}}function K(r){let e=r;return e.startsWith(`Error: Build failed with 1 error:
5
- `)&&(e=e.substring(r.indexOf(`
6
- `)+1)),e.startsWith("Error:")&&(e=e.substring(e.indexOf(":")+1)),e=e.trim(),`<html>
1
+ import{createRequire as e}from"node:module";import{decodePreviewableId as t}from"@cfp-studio/analyzer-api";import{RPCs as n}from"@cfp-studio/api";import{UNKNOWN_TYPE as r}from"@cfp-studio/type-analyzer";import{createFileSystemReader as i,createStackedReader as a}from"@cfp-studio/vfs";import o from"express";import s from"cors";import c from"fs-extra";import{createHttpTerminator as l}from"http-terminator";import u from"node:path";import d from"pino";import f from"pino-pretty";import{exclusivePromiseRunner as p}from"exclusive-promises";import m from"node:fs";import h,{fileURLToPath as g}from"node:url";import{globby as _}from"globby";import v from"node:net";import{assertNever as y}from"assert-never";import b from"axios";import x from"@fwouts/vite-tsconfig-paths";import{loadTsconfig as S}from"tsconfig-paths/lib/tsconfig-loader.js";import*as C from"vite";import{loadConfigFromFile as ee,searchForWorkspaceRoot as te,transformWithEsbuild as ne}from"vite";import{z as w}from"zod";import{escape as re}from"html-escaper";function ie(){let e=h.fileURLToPath(new URL(`.`,import.meta.url)),{version:t}=JSON.parse(m.readFileSync(u.resolve(e,`..`,`package.json`),`utf8`));return t}function T(e){try{return u.resolve(e,`node_modules`,`.cfp`,`v${ie()}`)}catch(e){throw Error(`无法获取 @cfp-studio/core 的版本号.\n${e}`)}}function ae(e){let t=u.resolve(e,`node_modules`,`.previewjs`);try{return m.existsSync(t)?(m.rmSync(t,{recursive:!0,force:!0}),!0):!1}catch{return!1}}async function E(e,t,n={}){let r=await D(e),i=u.relative(r,e),a=await _((i?i.split(u.sep).join(`/`)+`/`:``)+t,{gitignore:!0,ignore:[`**/node_modules/**`],cwd:r,absolute:!0,followSymbolicLinks:!1,suppressErrors:!0,deep:n.maxDepth}),o=e.replace(/\\/g,`/`);return o.endsWith(`/`)||(o+=`/`),a.filter(e=>e.startsWith(o)).sort()}async function D(e,t=e){try{if(await c.exists(u.join(e,`.git`)))return e;let n=u.dirname(e);return!n||n===e?t:D(n,t)}catch{return t}}const O=new Set([`jsconfig.json`,`tsconfig.json`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`]),oe=p();function se(e,n,r,i={}){return oe(async()=>{e.debug(`开始扫描组件,扫描参数: ${JSON.stringify(i)}`);let a=Date.now(),o=u.join(T(n.rootDir),`components.json`),s=await(async()=>{if(i.filePaths)return i.filePaths.map(e=>u.join(n.rootDir,e));e.debug(`扫描目录: ${n.rootDir},采集可扫描文件`);let t=await E(n.rootDir,`**/*.@(js|jsx|ts|tsx|svelte|vue)`);return e.debug(`找到 ${t.length} 个包含组件的文件`),t})(),l=new Set(s.map(e=>u.relative(n.rootDir,e).replace(/\\/g,`/`))),d={detectionStartTimestamp:0,components:[],stories:[]};if(c.existsSync(o))try{d=JSON.parse(c.readFileSync(o,`utf8`))}catch{e.warn(`无法转换 ${o} 中存储的缓存信息`)}d.detectionStartTimestamp<await A(n.rootDir)&&(d={detectionStartTimestamp:0,components:[],stories:[]});let f=s.filter(e=>{let t=n.reader.readSync(e);return t?.kind===`file`&&(i.forceRefresh||t.lastModifiedMillis()>=d.detectionStartTimestamp)}),p=new Set(f.map(e=>u.relative(n.rootDir,e).replace(/\\/g,`/`))),m=({id:e})=>{let n=t(e).filePath;return l.has(n)&&!p.has(n)},h=d.components.filter(m),g=d.stories.filter(m),{components:_,stories:v}=await k(e,n,r,f),y=[...h,..._],b=[...g,...v];if(!i.filePaths){await c.mkdirp(u.dirname(o));let e={detectionStartTimestamp:a,components:y,stories:b};await c.writeFile(o,JSON.stringify(e))}return{components:y,stories:b}})}async function k(e,t,n,r){let i=[],a=[];if(r.length===0)return{components:i,stories:a};e.debug(`在下述文件中查找组件:\n- ${r.map(e=>u.relative(t.rootDir,e)).join(`
2
+ - `)}`);let o=await n.crawlFiles(r);e.debug(`组件检测完成`);for(let e of o.components)i.push({id:e.id,sourcePosition:e.sourcePosition,exported:e.exported});for(let e of o.stories)a.push({id:e.id,sourcePosition:e.sourcePosition,associatedComponentId:e.associatedComponent?.id||null});return{components:i,stories:a}}async function A(e){let t=u.join(e,`node_modules`),n=0;if(await c.pathExists(t))for(let e of await c.readdir(t)){let r=u.join(t,e),i=await c.lstat(r);(i.isDirectory()||i.isSymbolicLink())&&(n=Math.max(n,i.mtimeMs))}for(let t of O){let r=u.join(e,t);if(await c.pathExists(r)){let e=await c.stat(r);n=Math.max(n,e.mtimeMs)}}return n}async function ce(e){for(let t=e;;t++)if(await le(t))return t}async function le(e){return new Promise(t=>{let n=v.createServer();n.unref(),n.on(`error`,()=>t(!1)),n.listen(e,()=>{n.close(()=>{t(!0)})})})}const ue=e(import.meta.url);async function j(e,t){let n=u.join(t,`package.json`);if(!await c.pathExists(n))return{};let{dependencies:r,devDependencies:i,peerDependencies:a}=JSON.parse(await c.readFile(n,`utf8`)),o={...r,...i,...a},s=new Map;for(let[n,r]of Object.entries(o)){let i=0;typeof r==`string`&&(i=r.startsWith(`^`)||r.startsWith(`~`)?Number.parseInt(r.slice(1)):Number.parseInt(r)),s.set(n,{majorVersion:i,readInstalledVersion:async()=>{try{let e=de(n,t),r=e;for(;r!==u.dirname(r);){let e=u.join(r,`package.json`);if(c.existsSync(e)){let t=JSON.parse(await c.readFile(e,`utf8`));if(typeof t.version==`string`)return t.version;throw Error(`包: ${e} 的版本号异常`)}r=u.dirname(r)}throw Error(`根据模块: ${e} 的入口路径无法找到 package.json`)}catch(t){return e.error(t,`无法读取包: ${n} 的安装版本, 你可能没有正确安装项目的依赖,请重新安装。`),null}}})}return Object.fromEntries(s)}function de(e,t){try{return ue.resolve(e,{paths:[t]})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`){let t=e.message.match(/No "exports" main defined in (.*)(\/|\\)package\.json/);if(t)return t[1]??``}throw e}}const M=[`preview.config.js`,`preview.config.mjs`,`preview.config.ts`,`preview.config.cjs`,`preview.config.mts`,`preview.config.cts`];async function fe(e,t){let n={};for(let r of M){let i=u.join(e,r);if(m.existsSync(i))try{let i=await ee({command:`serve`,mode:`development`},r,e,t);if(i){n=i.config;break}}catch(e){throw e instanceof Error&&typeof e.message==`string`&&e.message.includes(`config 必须导出或者返回一个对象`)?Error(`请使用一个 preview.config.js 的默认导出`):e}}return n}function N(e){let t=e;return t.startsWith(`Error: Build failed with 1 error:
3
+ `)&&(t=t.substring(e.indexOf(`
4
+ `)+1)),t.startsWith(`Error:`)&&(t=t.substring(t.indexOf(`:`)+1)),t=t.trim(),`<html>
7
5
  <head>
8
6
  <meta http-equiv="refresh" content="3">
9
7
  <style>
@@ -19,7 +17,7 @@ ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+
19
17
  }
20
18
  </style>
21
19
  <script>
22
- // \u6CE8\u610F: \u8981\u4E0E iframe/preview/index.html \u4E2D\u7684\u4EE3\u7801\u4FDD\u6301\u540C\u6B65
20
+ // 注意: 要与 iframe/preview/index.html 中的代码保持同步
23
21
  const sendPreviewEvent = event => (
24
22
  window.__PREVIEWJS_CONTROLLER__ || window.parent.__PREVIEWJS_CONTROLLER__
25
23
  ).onPreviewEvent(event);
@@ -29,12 +27,12 @@ ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+
29
27
  sendPreviewEvent({
30
28
  kind: "error",
31
29
  source: "load",
32
- message: ${JSON.stringify(r)}
30
+ message: ${JSON.stringify(e)}
33
31
  });
34
32
  <\/script>
35
33
  </head>
36
- <body>${Be(r)}</body>
37
- </html>`}const Je=new Set([".js",".jsx",".ts",".tsx"]),Le=/import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;function Ve(){return{name:"previewjs:css-modules-without-suffix",async transform(r,e){const t=e.split("?")[0];return!t||!Je.has(a.extname(t))?null:r.replace(Le,'import $1 from "$3.$4?$5&.module.css"')}}}function Ue(){return{name:"previewjs:invalidate-stories-modules-on-update",enforce:"post",transform:r=>r.includes("import.meta.hot.accept(")?`${r}
34
+ <body>${re(e)}</body>
35
+ </html>`}const pe=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]),me=/import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;function he(){return{name:`previewjs:css-modules-without-suffix`,async transform(e,t){let n=t.split(`?`)[0];return!n||!pe.has(u.extname(n))?null:e.replace(me,`import $1 from "$3.$4?$5&.module.css"`)}}}const P=`__fakeValueExport__`;let F=null;function I(){return F??=import(`typescript`).then(e=>e.default??e),F}function L(e){let t=new Map;return{name:`cfp:fake-type-exports`,async transform(n,r){if(!r.endsWith(`.ts`)&&!r.endsWith(`.tsx`)||r.endsWith(`.d.ts`))return;let i=await e.readFile(r);if(i===null||!i.includes(`export`))return;let a=t.get(r);if((a===void 0||a.text!==i)&&(a={text:i,names:await R(r,i)},t.set(r,a)),a.names.length!==0)return`${n}\nconst ${P} = null;\nexport { ${a.names.map(e=>`${P} as ${e}`).join(`, `)} };`}}}async function R(e,t){let n=await I(),r=e.endsWith(`.tsx`);return ge(n,n.createSourceFile(e,t,n.ScriptTarget.Latest,!1,r?n.ScriptKind.TSX:n.ScriptKind.TS))}function ge(e,t){let n=new Set,r=new Set,i=new Map,a=(e,{asType:t,asValue:n})=>{let r=i.get(e)??{asType:!1,asValue:!1};r.asType=r.asType||t===!0,r.asValue=r.asValue||n===!0,i.set(e,r)};for(let i of t.statements){let t=_e(e,i);if(e.isTypeAliasDeclaration(i)||e.isInterfaceDeclaration(i)){let e=i.name.text;n.add(e),t&&a(e,{asType:!0});continue}if(e.isClassDeclaration(i)||e.isEnumDeclaration(i)){if(!i.name)continue;let e=i.name.text;n.add(e),r.add(e),t&&a(e,{asType:!0,asValue:!0});continue}if(e.isFunctionDeclaration(i)){if(!i.name)continue;let e=i.name.text;r.add(e),t&&a(e,{asValue:!0});continue}if(e.isVariableStatement(i)){for(let n of i.declarationList.declarations){if(!e.isIdentifier(n.name))continue;let i=n.name.text;r.add(i),t&&a(i,{asValue:!0})}continue}if(e.isExportDeclaration(i)&&i.exportClause&&!i.moduleSpecifier&&e.isNamedExports(i.exportClause))for(let e of i.exportClause.elements){let t=(e.propertyName??e.name).text;a(t,{asType:!0,asValue:!i.isTypeOnly})}}let o=[];for(let[e,t]of i)n.has(e)&&(t.asValue&&r.has(e)||o.push(e));return o}function _e(e,t){let n=t.modifiers;return n!==void 0&&n.some(t=>t.kind===e.SyntaxKind.ExportKeyword)}function ve(){return{name:`previewjs:invalidate-stories-modules-on-update`,enforce:`post`,transform:e=>e.includes(`import.meta.hot.accept(`)?`${e}
38
36
  if (import.meta?.hot) {
39
37
  import.meta.hot.accept(newModule => {
40
38
  if (newModule?.default?.component) {
@@ -42,20 +40,20 @@ ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+
42
40
  }
43
41
  });
44
42
  }
45
- `:null}}function Ge(){return{name:"previewjs:local-eval",enforce:"post",transform:(r,e)=>e.indexOf("/node_modules/")!==-1||e.indexOf("?")!==-1?null:`${r}
43
+ `:null}}function ye(){return{name:`previewjs:local-eval`,enforce:`post`,transform:(e,t)=>t.indexOf(`/node_modules/`)!==-1||t.indexOf(`?`)!==-1?null:`${e}
46
44
  export const PreviewJsEval = (code, args = {}) => {
47
45
  return eval("(({ " + Object.keys(args).join(", ") + "}) => { " + code + " })(args)");
48
46
  }
49
- `}}const ne="/__previewjs_internal__/preview.js?p=";function ze(){return{name:"previewjs:preview-script",load(r){if(!r.startsWith(ne))return null;const e=r.substring(ne.length),t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return qe(t)}}}function qe({previewablePath:r,previewableName:e,wrapperPath:t,wrapperName:o,detectedGlobalCssFilePaths:i}){return`
50
- // \u5BFC\u5165\u521D\u59CB\u5316\u76D1\u542C\u5668\u548C\u9884\u89C8\u7684\u51FD\u6570
47
+ `}}function be(){return{name:`previewjs:preview-script`,load(e){if(!e.startsWith(`/__previewjs_internal__/preview.js?p=`))return null;let t=e.substring(37);return xe(JSON.parse(Buffer.from(t,`base64url`).toString(`utf8`)))}}}function xe({previewablePath:e,previewableName:t,wrapperPath:n,wrapperName:r,detectedGlobalCssFilePaths:i}){return`
48
+ // 导入初始化监听器和预览的函数
51
49
  import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";
52
- // \u521D\u59CB\u5316\u76D1\u542C\u5668
50
+ // 初始化监听器
53
51
  initListeners();
54
- // \u542F\u7528\u70ED\u66F4\u65B0
52
+ // 启用热更新
55
53
  import.meta.hot.accept();
56
- // \u521D\u59CB\u5316\u5237\u65B0\u51FD\u6570
54
+ // 初始化刷新函数
57
55
  let refresh = () => {};
58
- // \u4E3A\u7A97\u53E3\u7684 __PREVIEWJS_IFRAME__ \u5BF9\u8C61\u6DFB\u52A0\u5237\u65B0\u65B9\u6CD5
56
+ // 为窗口的 __PREVIEWJS_IFRAME__ 对象添加刷新方法
59
57
  window.__PREVIEWJS_IFRAME__.refresh = (options) => {
60
58
  refresh(options);
61
59
  if (options.refetchPreviewableModule) {
@@ -71,8 +69,8 @@ ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+
71
69
  }));
72
70
  }
73
71
  };
74
- // \u76D1\u542C\u53EF\u9884\u89C8\u6A21\u5757\u7684\u70ED\u66F4\u65B0
75
- import.meta.hot.accept(["/${r}"], ([previewableModule]) => {
72
+ // 监听可预览模块的热更新
73
+ import.meta.hot.accept(["/${e}"], ([previewableModule]) => {
76
74
  if (previewableModule) {
77
75
  refresh({
78
76
  previewableModule,
@@ -80,49 +78,49 @@ ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+
80
78
  }
81
79
  });
82
80
 
83
- ${t?`
84
- const wrapperModulePromise = import(/* @vite-ignore */ "/${t}?t=" + Date.now());
85
- // \u76D1\u542C\u5305\u88C5\u5668\u6A21\u5757\u7684\u70ED\u66F4\u65B0
86
- import.meta.hot.accept(["/${t}"], ([wrapperModule]) => {
81
+ ${n?`
82
+ const wrapperModulePromise = import(/* @vite-ignore */ "/${n}?t=" + Date.now());
83
+ // 监听包装器模块的热更新
84
+ import.meta.hot.accept(["/${n}"], ([wrapperModule]) => {
87
85
  if (wrapperModule) {
88
- // \u8C03\u7528\u5237\u65B0\u51FD\u6570\u66F4\u65B0\u9884\u89C8
86
+ // 调用刷新函数更新预览
89
87
  refresh({
90
88
  wrapperModule,
91
89
  });
92
90
  }
93
91
  });
94
92
  `:`
95
- const wrapperModulePromise = Promise.all([${i.map(s=>`import(/* @vite-ignore */ "/${s.replace(/\\/g,"/")}").catch(() => null)`).join(",")}]).then(() => null);
93
+ const wrapperModulePromise = Promise.all([${i.map(e=>`import(/* @vite-ignore */ "/${e.replace(/\\/g,`/`)}").catch(() => null)`).join(`,`)}]).then(() => null);
96
94
  `}
97
95
 
98
96
  // Important: the wrapper must be loaded first as it may monkey-patch
99
97
  // modules imported by the component module.
100
98
  wrapperModulePromise.then(wrapperModule => {
101
- // \u52A0\u8F7D\u65B0\u7684\u53EF\u9884\u89C8\u6A21\u5757
99
+ // 加载新的可预览模块
102
100
  loadFreshPreviewableModule().then(previewableModule => {
103
- // \u521D\u59CB\u5316\u9884\u89C8\u5E76\u66F4\u65B0\u5237\u65B0\u51FD\u6570
101
+ // 初始化预览并更新刷新函数
104
102
  refresh = initPreview({
105
103
  previewableModule,
106
- previewableName: ${JSON.stringify(e)},
104
+ previewableName: ${JSON.stringify(t)},
107
105
  wrapperModule,
108
- wrapperName: ${JSON.stringify(o)},
106
+ wrapperName: ${JSON.stringify(r)},
109
107
  });
110
108
  });
111
109
  });
112
110
 
113
111
  /**
114
- * \u52A0\u8F7D\u65B0\u7684\u53EF\u9884\u89C8\u6A21\u5757
115
- * @returns {Promise<any>} - \u8FD4\u56DE\u4E00\u4E2A Promise\uFF0C\u89E3\u6790\u4E3A\u52A0\u8F7D\u7684\u53EF\u9884\u89C8\u6A21\u5757
112
+ * 加载新的可预览模块
113
+ * @returns {Promise<any>} - 返回一个 Promise,解析为加载的可预览模块
116
114
  */
117
115
  function loadFreshPreviewableModule() {
118
- return import(/* @vite-ignore */ "/${r}?t=" + Date.now());
116
+ return import(/* @vite-ignore */ "/${e}?t=" + Date.now());
119
117
  }
120
118
 
121
119
  /**
122
- * \u52A0\u8F7D\u65B0\u7684wrapper\u6A21\u5757
123
- * @returns {Promise<any>} - \u8FD4\u56DE\u4E00\u4E2A Promise\uFF0C\u89E3\u6790\u4E3A\u52A0\u8F7D\u7684wrapper\u6A21\u5757
120
+ * 加载新的wrapper模块
121
+ * @returns {Promise<any>} - 返回一个 Promise,解析为加载的wrapper模块
124
122
  */
125
123
  function loadFreshWrapperModule() {
126
- return import(/* @vite-ignore */ "/${t}?t=" + Date.now());
124
+ return import(/* @vite-ignore */ "/${n}?t=" + Date.now());
127
125
  }
128
- `}function Ke({rootDir:r,publicDir:e}){return{name:"previewjs:public-asset-import",resolveId:async(t,o)=>{if(!o||!t.startsWith("/")||t.startsWith("/__previewjs__/"))return null;const i=a.join(r,e),s=a.join(i,t);return!s.startsWith(i+a.sep)||!await w.pathExists(s)?null:t}}}function Q(r){let e=r;return e.match(/^[a-z]:/)&&(e=e[0]?.toUpperCase()+r.substring(1)),e.replace(/\\/g,"/")}const $="/@cfp-studio-virtual:",W="/@id/__x00__",N=new Set([".js",".jsx",".ts",".tsx"]);function ae(r){let e=r;return e.startsWith($)&&(e=e.slice($.length)),e.startsWith("\0")&&(e=e.slice(1)),e.startsWith(W)&&(e=e.slice(W.length)),[e,e!==r]}function Qe(r){const{reader:e,rootDir:t}=r;return{name:"previewjs:virtual-fs",resolveId:async(s,n)=>{const[u,l]=n?ae(n):[null,!1];if(s.indexOf("/node_modules/")!==-1)return null;let[p]=ae(s);p=p.split("?",2)[0]??"";const d=a.extname(p);let f;if(a.isAbsolute(p))f=p;else{if(!u)return null;if(d&&!N.has(d)&&d!==".svg")return a.join(a.dirname(u),p);f=a.join(a.dirname(u),p)}const g=await o(f);if(g){const[m]=g;return await w.pathExists(m)&&!l?null:(f.endsWith(d)||(f+=d),$+m.replace(/\\/g,"/"))}return null},load:async s=>{let n=s;if(n.indexOf("/node_modules/")!==-1)return null;n.startsWith($)&&(n=n.slice($.length)),n.startsWith("\0")&&(n=n.slice(1)),n.startsWith(W)&&(n=n.slice(W.length));const u=await o(n);if(!u)return null;const[l,p]=u;let d=!1;for(const y of r.allowedAbsolutePaths){const D=a.relative(y,l);if(D&&!D.startsWith("..")&&!a.isAbsolute(D)){d=!0;break}}if(!d)return r.logger.error(`\u8BD5\u56FE\u8BBF\u95EE\u7684 ${l} \u6587\u4EF6\u5728\u8FD0\u884C\u8BBF\u95EE\u7684\u76EE\u5F55\u4E4B\u5916. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(p.kind!=="file")return r.logger.error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\uFF1A${l}`),null;const f=await p.read(),g=a.extname(l);if(!N.has(g))return f;const m=a.extname(s);return{code:!s.includes("__previewjs_internal__")&&(m===""||m===".js")?(await Ae(f,l,{loader:l.endsWith(".ts")?"ts":"tsx",format:"esm",target:"es2020",sourcefile:a.relative(t,l),...r.esbuildOptions})).code:f}},transform:(s,n)=>n.startsWith($)?{code:s,map:{mappings:"",names:[],sources:[],version:3}}:null,handleHotUpdate:async s=>{const n=r.moduleGraph();if(!n)return null;const u=a.relative(t,s.file),l=a.join(t,u),p=await e.read(l);if(!p||p.kind!=="file")return null;const d=$+Q(l),f=n.getModuleById(d);return f&&[f]}};async function o(s){return await i(s)||await i(a.join(t,s))}async function i(s){for(const n of["",...N,...[...N].map(u=>`${a.sep}index${u}`)]){const u=`${s}${n}`,l=await e.read(u);if(l?.kind==="file")return[u,l]}return null}}const Ye=()=>({name:"inspector-server-plugin",configureServer(r){r.middlewares.use(xe)}});var Xe=Object.defineProperty,Ze=(r,e,t)=>e in r?Xe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,et=(r,e,t)=>(Ze(r,typeof e!="symbol"?e+"":e,t),t),ue=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)},b=(r,e,t)=>(ue(r,e,"read from private field"),t?t.call(r):e.get(r)),Y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},I=(r,e,t,o)=>(ue(r,e,"write to private field"),o?o.call(r,t):e.set(r,t),t),C,B,T;const tt=[".postcssrc",".postcssrc.json",".postcssrc.yml",".postcssrc.js",".postcssrc.mjs",".postcssrc.cjs",".postcssrc.ts","postcss.config.js","postcss.config.mjs","postcss.config.cjs","postcss.config.ts"],le=["index","global","globals","style","styles","app"],ce=["css","sass","scss","less","styl","stylus"],rt=le.flatMap(r=>ce.map(e=>`${r}.${e}`)),it=new Set([...je,...se,...tt,...rt,"vite.config.js","vite.config.ts","svelte.config.js"]);async function H(r){return r?.kind==="starting"?r.promise:r}class st{constructor(e){this.options=e,et(this,"middleware"),Y(this,C,null),Y(this,B,void 0),Y(this,T,{onChange:(o,i)=>{this.onFileChanged(a.resolve(o),i).catch(s=>this.options.logger.error(s))}});const t=R.Router();t.use(async(o,i,s)=>{const n=await H(b(this,C));if(!n||n.kind==="error")return s();try{n.viteServer.middlewares(o,i,s)}catch(u){this.options.logger.error(`Vite middleware error: ${u}`),i.status(500).end(`Vite middleware error: ${u}`)}}),this.middleware=t,I(this,B,ee())}get state(){return b(this,C)}async loadIndexHtml(e,t){return b(this,B).call(this,async()=>{try{const o=await H(b(this,C));if(!o)return K("Vite server is not running");if(o.kind==="error")return K(o.error);const i=await w.readFile(this.options.shadowHtmlFilePath,"utf-8"),{config:s,viteServer:n}=o,{filePath:u,name:l}=O(t),p=u.replace(/\\/g,"/"),d=s.wrapper,f=d&&await w.pathExists(a.join(this.options.rootDir,d.path))?d.path.replace(/\\/g,"/"):null;return await n.transformIndexHtml(e,i.replace("<!-- %OPTIONAL_HEAD_CONTENT% -->",`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(JSON.stringify({previewablePath:p,previewableName:l,wrapperPath:f,wrapperName:d?.componentName||null,detectedGlobalCssFilePaths:s.detectedGlobalCssFilePaths}),"utf8").toString("base64url")}"><\/script>`))}catch(o){return K(`${o}`)}})}async start(){let e;I(this,C,{kind:"starting",promise:new Promise(t=>{e=o=>{I(this,C,o),t(o)}})}),this.options.reader.listeners.add(b(this,T));try{process.chdir(this.options.rootDir);const t=await $e(this.options.rootDir,pe(this.options.logger)),o=await re(this.options.rootDir,`**/@(${le.join("|")}).@(${ce.join("|")})`,{maxDepth:3}),i={...t,wrapper:t.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:o.map(v=>a.relative(this.options.rootDir,v))},s=[];let n=null;for(const v of["tsconfig.json","jsconfig.json"]){const E=a.join(this.options.rootDir,v);try{if(await w.pathExists(E)){const c=Se(E)||null;if(c){n=nt.parse(c);break}}}catch(c){this.options.logger.warn(`Unable to load tsconfig from ${E}: ${c}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(n||null,null,2)}`);const u=n?.compilerOptions?.baseUrl||"",l=n?.compilerOptions?.paths||{};let p=u.startsWith("./")?u.substring(1):u;p&&!p.endsWith("/")&&(p+="/");for(const[v,E]of Object.entries(l)){const c=E[0];if(!c)continue;const h=v.endsWith("/*")?v.slice(0,v.length-2):v,P=c.endsWith("/*")?c.slice(0,c.length-2):c;s.push({find:h,replacement:a.join(this.options.rootDir,u,P)})}const d=await q.loadConfigFromFile({command:"serve",mode:"development"},void 0,this.options.rootDir),f=q.createLogger(pe(this.options.logger)),g=this.options.frameworkPlugin.viteConfig(await X([...d?.config.plugins||[],...i.vite?.plugins||[]])),m=i.vite?.publicDir||d?.config.publicDir||g.publicDir||i.publicDir||"public",y=ot(this.options.reader,await X([Pe({root:this.options.rootDir}),ze(),Qe({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:i.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[_e(this.options.rootDir)],moduleGraph:()=>b(this,C)?.kind==="running"?b(this,C).viteServer.moduleGraph:null,esbuildOptions:g.esbuild||{}}),Ge(),Ye(),Ue(),ke({readFile:v=>this.options.reader.read(v).then(E=>E?.kind!=="file"?null:E.read())}),Ve(),Ke({rootDir:this.options.rootDir,publicDir:m}),g.plugins]));this.options.logger.debug("Creating Vite server");const D=await q.createServer({...g,...d?.config,...i.vite,configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,hmr:{overlay:!1,server:this.options.server,clientPort:this.options.clientPort||this.options.port,...typeof i.vite?.server?.hmr=="object"?i.vite?.server?.hmr:{}},fs:{strict:!1,...i.vite?.server?.fs||{}},...i.vite?.server},customLogger:{info:f.info,warn:f.warn,error:(v,E)=>{v.startsWith("\x1B[31mInternal server error")||b(this,C)?.kind==="running"&&b(this,C).viteServer.ws.send({type:"error",err:{message:v,stack:""}}),f.error(v,E)},warnOnce:f.warnOnce,clearScreen:()=>{},hasWarned:f.hasWarned,hasErrorLogged:f.hasErrorLogged},clearScreen:!1,cacheDir:i.vite?.cacheDir||d?.config.cacheDir||this.options.cacheDir,publicDir:m,plugins:y,define:{__filename:void 0,__dirname:void 0,process:void 0,...g.define,...d?.config.define,...i.vite?.define},resolve:{...d?.config.resolve,...i.vite?.resolve,alias:[...J(i.vite?.resolve?.alias),...J(i.alias),...J(d?.config.resolve?.alias),...s,{find:/^~(.*)/,replacement:`${p}$1`},{find:"@",replacement:p},...J(g.resolve?.alias)]}});e({kind:"running",config:i,viteServer:D}),this.options.logger.debug("Done starting Vite server")}catch(t){this.options.logger.error(`Vite startup error: ${t}`),e({kind:"error",error:t.stack||t.message})}return b(this,C).promise}async stop({restart:e}={restart:!1}){await b(this,B).call(this,async()=>{this.options.reader.listeners.remove(b(this,T));const t=await H(b(this,C));return t?.kind==="running"&&await t.viteServer.close(),e?this.start():I(this,C,null)})}async onFileChanged(e,t){const o=await H(this.state);if(!o)return;if(!t.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(a.relative(this.options.rootDir,e)),it.has(a.basename(e)))){this.options.logger.info("New dependencies were detected. Restarting..."),await this.stop({restart:!0});return}if(o.kind!=="running")return;const{viteServer:i,config:s}=o;if(t.virtual){const n=await i.moduleGraph.getModulesByFile(Q(e));for(const u of n||[])if(u.id)try{const l=await i.pluginContainer.load(u.id);if(!l)continue;const p=typeof l=="object"?l.code:l;await i.pluginContainer.transform(p,u.id)}catch{return}for(const u of i.watcher.listeners("change"))u(e)}else s.wrapper&&e===a.resolve(this.options.rootDir,s.wrapper.path)&&(i.moduleGraph.invalidateAll(),i.ws.send({type:"full-reload"}))}}C=new WeakMap,B=new WeakMap,T=new WeakMap;function J(r){return r?Array.isArray(r)?r:Object.entries(r).map(([e,t])=>({find:e,replacement:t})):[]}async function X(r){const e=[];for(const t of await Promise.all(r))t&&(Array.isArray(t)?e.push(...await X(t)):e.push(t));return e}function pe(r){switch(r.level){case"fatal":return"silent";case"error":return"error";case"warn":return"warn";case"info":return"info";case"debug":return"info";case"trace":return"info";case"silent":return"silent";default:return r.warn(`Unknown log level: ${r.level}`),"info"}}function ot(r,e){return e.map(async t=>{if(!t.handleHotUpdate)return t;const o=typeof t.handleHotUpdate=="function"?t.handleHotUpdate:t.handleHotUpdate.handler;return{...t,handleHotUpdate:async i=>{await o({...i,read:async()=>{const s=await r.read(i.file);return s?.kind!=="file"?i.read():s.read()}})}}})}const nt=A.object({compilerOptions:A.object({baseUrl:A.string().optional(),paths:A.record(A.array(A.string())).optional()}).optional()});var at=Object.defineProperty,ut=(r,e,t)=>e in r?at(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,L=(r,e,t)=>(ut(r,typeof e!="symbol"?e+"":e,t),t);class lt{constructor(e){this.options=e,L(this,"transformingReader"),L(this,"viteManager",null),L(this,"status",{kind:"stopped"}),L(this,"disposeObserver",null),this.transformingReader=he([e.reader,z({mapping:{from:e.frameworkPlugin.previewDirPath,to:a.join(e.rootDir,"__previewjs_internal__","renderer")},watch:!1}),z({mapping:{from:e.previewDirPath,to:e.rootDir},watch:!1})])}async start(){const e=this.status;switch(e.kind){case"starting":try{await e.promise}catch(t){this.options.logger.error(t),this.status={kind:"stopped"},await this.startFromStopped()}break;case"started":break;case"stopping":try{await e.promise}catch(t){this.options.logger.error(t),this.status={kind:"stopped"}}await this.start();break;case"stopped":await this.startFromStopped();break;default:throw De(e)}}async startFromStopped(){this.status={kind:"starting",promise:(async()=>{const e=R.Router();if(e.use((i,s,n)=>{s.setHeader("Cache-Control","max-age=0, must-revalidate"),n()}),e.use(this.options.middlewares),e.get(/^\/.*:[^/]+\/$/,async(i,s,n)=>{const u=i.header("Accept");if(i.url.includes("?html-proxy")){n();return}if(u==="text/x-vite-ping"){s.writeHead(204).end();return}const l=i.path.substring(1,i.path.length-1);if(!this.viteManager){s.status(404).end("Vite\u670D\u52A1\u5668\u672A\u542F\u52A8");return}s.status(200).set({"Content-Type":"text/html"}).end(await this.viteManager.loadIndexHtml(i.originalUrl,l))}),e.use("/ping",async(i,s)=>{s.json(JSON.stringify({pong:"match!"}))}),e.use((i,s,n)=>{this.viteManager?.middleware(i,s,n)}),this.transformingReader.observe)try{this.disposeObserver=await this.transformingReader.observe(this.options.rootDir)}catch(i){this.options.logger.error(i,"\u542F\u52A8\u6587\u4EF6\u7CFB\u7EDF\u76D1\u542C\u5931\u8D25:")}const{server:t,disposeHttpServer:o}=await this.options.getHttpServer(e);this.options.logger.debug("\u542F\u52A8 Vite manager ..."),this.viteManager=new st({rootDir:this.options.rootDir,shadowHtmlFilePath:a.join(this.options.previewDirPath,"index.html"),reader:this.transformingReader,cacheDir:a.join(te(this.options.rootDir),"vite"),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:t,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug("\u9884\u89C8\u670D\u52A1\u5DF2\u5C31\u7EEA"),this.status={kind:"started",onStop:o}})()},await this.status.promise;for(let e=0;;e++)try{await be.get(`http://localhost:${this.options.port}`);break}catch(t){if(e===10)throw t;await new Promise(o=>setTimeout(o,50))}}async stop(){if(this.status.kind==="starting")try{await this.status.promise}catch{this.status={kind:"stopped"}}if(this.status.kind!=="started")return;const e=this.status.onStop;this.status={kind:"stopping",promise:(async()=>{await this.disposeObserver?.(),this.disposeObserver=null,await this.viteManager?.stop(),this.viteManager=null,await e(),this.status={kind:"stopped"}})()},await this.status.promise}}var ct=Object.defineProperty,pt=(r,e,t)=>e in r?ct(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,de=(r,e,t)=>(pt(r,typeof e!="symbol"?e+"":e,t),t);class dt{constructor(e){this.logger=e,de(this,"handlers",new Map),de(this,"registerRPC",(t,o)=>{if(this.handlers.has(t.path))throw new Error(`\u7AEF\u70B9 '${t.path}' \u5DF2\u7ECF\u6CE8\u518C\u4E86 handler\uFF0C\u662F\u5426\u91CD\u590D\u6CE8\u518C\uFF1F`);this.handlers.set(t.path,o)})}async handle(e,t){const o=this.handlers.get(e);if(!o)return{kind:"error",message:`\u8DEF\u5F84 '${e}' \u6CA1\u6709\u6CE8\u518C\u5BF9\u5E94\u7684 handler`};this.logger.debug(`RPC ${e} invoked`);try{return{kind:"success",response:await o(t)}}catch(i){return this.logger.error(`RPC ${e} failed: ${i}`),i instanceof Error?{kind:"error",message:i.message}:{kind:"error",message:`${i}`}}}}async function ft(r,e,t){const o=await oe(r,e);for(const i of t)if(i.info&&await i.isCompatible(o))return i.info?.name;return null}const{pino:ht}=we,mt=ve,gt=Z(import.meta.url);process.on("uncaughtException",r=>{console.error("Core \u9047\u5230\u672A\u6355\u83B7\u7684\u5F02\u5E38",r)}),process.on("unhandledRejection",r=>{console.error("Core \u9047\u5230\u672A\u5904\u7406\u7684 Promise \u5BF9\u8C61",r)});async function wt({rootDir:r,frameworkPlugin:e,logger:t=ht({level:process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase()||"warn"},mt({colorize:!0})),reader:o=z(),onServerStart:i=()=>Promise.resolve({})}){if(!e.info)throw new Error("\u63D0\u4F9B\u7684 framework plugin \u4E0E\u5F53\u524D\u7248\u672C Preview.js \u4E0D\u9002\u914D. \u8BF7\u5347\u7EA7.");if(e.info.apiVersion>5)throw new Error(`Preview.js \u7684 framework plugin ${e.info.name} \u592A\u65B0\u4E86. \u8BF7\u5347\u7EA7 Preview.js \u6216\u8005\u4F7F\u7528 ${e.info.name} \u7684\u8F83\u65E9\u7248\u672C.`);const s=await oe(t,r);if(!await e.isCompatible(s))throw new Error(`Preview.js \u7684 framework plugin ${e.info.name} \u4E0E\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u4F9D\u8D56\u4E0D\u517C\u5BB9\u3002`);t.info(`\u4F7F\u7528 ${e.info.name} \u5728\u76EE\u5F55: ${r} \u4E2D\u521B\u5EFA\u5DE5\u4F5C\u533A`);const n=await e.create({rootDir:r,reader:o,logger:t,dependencies:s}),u=new Set,l={frameworkPluginName:e.info.name,crawlFiles:n.crawlFiles,typeAnalyzer:n.typeAnalyzer,rootDir:r,reader:o,startServer:async({asMiddleware:p,port:d,clientPort:f,onStop:g}={})=>{const m=d||await Ne(3140),y=new dt(t);y.registerRPC(G.Analyze,async({previewableIds:c})=>{t.debug(`\u5206\u6790: ${c.join(", ")}`);const h=await n.crawlFiles([...new Set(c.map(F=>a.join(r,O(F).filePath)))]);t.debug(`\u68C0\u6D4B\u5230 ${h.components.length} \u4E2A\u7EC4\u4EF6\u548C ${h.stories.length} \u4E2Astory`);const P=[],V=Object.fromEntries(h.components.map(F=>[F.id,F])),U=Object.fromEntries(h.stories.map(F=>[F.id,F]));let k={};for(const F of c){const x=V[F],S=U[F];let M;if(x){t.debug(`\u5206\u6790\u7EC4\u4EF6: ${F}`);let j;({props:j,types:M}=await x.analyze()),t.debug(`\u5B8C\u6210\u7EC4\u4EF6: ${F} \u5206\u6790`),P.push({kind:"component",id:F,exported:x.exported,sourcePosition:x.sourcePosition,props:j})}else if(S){let j;S.associatedComponent?(t.debug(`\u5206\u6790 story: ${F}`),{props:j,types:M}=await S.associatedComponent.analyze(),t.debug(`\u5B8C\u6210 story: ${F} \u5206\u6790`),t.debug(`props: ${JSON.stringify(j)}`),t.debug(`types: ${JSON.stringify(k)}`)):(t.debug(`story: ${F} \u6CA1\u6709\u5173\u8054\u7684\u7EC4\u4EF6`),j=fe,M={});let _=null;({args:_}=await S.analyze()),P.push({kind:"story",id:F,sourcePosition:S.sourcePosition,associatedComponentId:S.associatedComponent?.id||null,props:j,args:_}),t.debug(`story args: ${JSON.stringify(_)}`)}else{const{filePath:j,name:_}=O(F);throw new Error(`\u5728 ${j} \u4E2D\u672A\u627E\u5230\u7EC4\u4EF6 ${_}. `)}k={...k,...M}}return{previewables:P,types:k}}),y.registerRPC(G.GetInfo,async()=>({frameworkPlugin:e.info})),y.registerRPC(G.CrawlFiles,c=>Oe(t,l,n,c));const D=[me(),R.json(),async(c,h,P)=>{c.path.startsWith("/api/")?h.json(await y.handle(c.path.substr(5),c.body)):P()}];if(i){const{middlewares:c=[]}=await i({registerRPC:(h,P)=>y.registerRPC(h,P),workspace:l});D.push(...c)}const v=p?async c=>{const h=p.register(c);return{server:p.server,disposeHttpServer:async()=>{h()}}}:async c=>{t.debug("\u542F\u52A8 Express \u670D\u52A1\u5668");const h=R();h.use(c);const P=await new Promise(U=>{const k=h.listen(m,()=>{t.info(`Preview.js \u9884\u89C8\u670D\u52A1\u8FD0\u884C\u5728 http://localhost:${m}.`),U(k)})}),V=ge({server:P,gracefulTerminationTimeout:0});return{server:P,disposeHttpServer:async()=>{await V.terminate(),t.info("Preview.js \u9884\u89C8\u670D\u52A1\u5668\u5DF2\u505C\u6B62.")}}},E=new lt({reader:o,rootDir:r,previewDirPath:a.join(a.dirname(a.dirname(gt.resolve("@cfp-studio/iframe"))),"preview"),frameworkPlugin:n,logger:t,middlewares:D,getHttpServer:v,port:m,clientPort:f});return await E.start(),u.add(E),{port:m,stop:async()=>{u.delete(E),await E.stop(),await g?.()}}},dispose:async()=>{await Promise.all([...u].map(p=>p.stop())),u.clear(),n.dispose()}};return l}function vt(r){let e=a.resolve(r);for(;e!==a.dirname(e);){if(w.existsSync(a.join(e,"package.json")))return e;e=a.dirname(e)}return null}export{wt as createWorkspace,ft as findCompatiblePlugin,vt as findWorkspaceRoot,Q as toVitePath};
126
+ `}function Se({rootDir:e,publicDir:t}){return{name:`previewjs:public-asset-import`,resolveId:async(n,r)=>{if(!r||!n.startsWith(`/`)||n.startsWith(`/__previewjs__/`))return null;let i=u.join(e,t),a=u.join(i,n);return!a.startsWith(i+u.sep)||!await c.pathExists(a)?null:n}}}function z(e){let t=e;return t.match(/^[a-z]:/)&&(t=t[0]?.toUpperCase()+e.substring(1)),t.replace(/\\/g,`/`)}const B=`/@cfp-studio-virtual:`,V=`/@id/__x00__`,H=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]);function U(e){let t=e;return t.startsWith(B)&&(t=t.slice(21)),t.startsWith(`\0`)&&(t=t.slice(1)),t.startsWith(V)&&(t=t.slice(12)),[t,t!==e]}function Ce(e){let{reader:t,rootDir:n}=e;return{name:`previewjs:virtual-fs`,resolveId:async(e,t)=>{let[n,i]=t?U(t):[null,!1];if(e.indexOf(`/node_modules/`)!==-1)return null;let[a]=U(e);a=a.split(`?`,2)[0]??``;let o=u.extname(a),s;if(u.isAbsolute(a))s=a;else{if(!n)return null;if(o&&!H.has(o)&&o!==`.svg`)return u.join(u.dirname(n),a);s=u.join(u.dirname(n),a)}let l=await r(s);if(l){let[e]=l;return await c.pathExists(e)&&!i?null:(s.endsWith(o)||(s+=o),B+e.replace(/\\/g,`/`))}return null},load:async t=>{let i=t;if(i.indexOf(`/node_modules/`)!==-1)return null;i.startsWith(B)&&(i=i.slice(21)),i.startsWith(`\0`)&&(i=i.slice(1)),i.startsWith(V)&&(i=i.slice(12));let a=await r(i);if(!a)return null;let[o,s]=a,c=!1;for(let t of e.allowedAbsolutePaths){let e=u.relative(t,o);if(e&&!e.startsWith(`..`)&&!u.isAbsolute(e)){c=!0;break}}if(!c)return e.logger.error(`试图访问的 ${o} 文件在运行访问的目录之外. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(s.kind!==`file`)return e.logger.error(`无法读取文件:${o}`),null;let l=await s.read(),d=u.extname(o);if(!H.has(d))return l;let f=u.extname(t);return{code:!t.includes(`__previewjs_internal__`)&&(f===``||f===`.js`)?(await ne(l,o,{loader:o.endsWith(`.ts`)?`ts`:`tsx`,format:`esm`,target:`es2020`,sourcefile:u.relative(n,o),...e.esbuildOptions})).code:l}},transform:(e,t)=>t.startsWith(B)?{code:e,map:{mappings:``,names:[],sources:[],version:3}}:null,handleHotUpdate:async r=>{let i=e.moduleGraph();if(!i)return null;let a=u.relative(n,r.file),o=u.join(n,a),s=await t.read(o);if(!s||s.kind!==`file`)return null;let c=B+z(o),l=i.getModuleById(c);return l&&[l]}};async function r(e){return await i(e)||await i(u.join(n,e))}async function i(e){for(let n of[``,...H,...[...H].map(e=>`${u.sep}index${e}`)]){let r=`${e}${n}`,i=await t.read(r);if(i?.kind===`file`)return[r,i]}return null}}const W=e(import.meta.url);function G(e){let t=we(e);if(!t)return e;let n=u.join(u.dirname(u.dirname(t)),`src`,`index.ts`);return c.existsSync(n)?n:t}function we(e){let t=[Te];try{t.push(u.dirname(W.resolve(`@cfp-studio/iframe/package.json`)))}catch{}for(let n of t)try{return W.resolve(e,{paths:[n]})}catch{}}const Te=u.dirname(g(import.meta.url)),Ee=[`.postcssrc`,`.postcssrc.json`,`.postcssrc.yml`,`.postcssrc.js`,`.postcssrc.mjs`,`.postcssrc.cjs`,`.postcssrc.ts`,`postcss.config.js`,`postcss.config.mjs`,`postcss.config.cjs`,`postcss.config.ts`],K=[`index`,`global`,`globals`,`style`,`styles`,`app`],q=[`css`,`sass`,`scss`,`less`,`styl`,`stylus`],De=K.flatMap(e=>q.map(t=>`${e}.${t}`)),Oe=new Set([...M,...O,...Ee,...De,`vite.config.js`,`vite.config.ts`,`svelte.config.js`]);async function J(e){return e?.kind===`starting`?e.promise:e}var ke=class{#e=null;#t;#n={onChange:(e,t)=>{this.onFileChanged(u.resolve(e),t).catch(e=>this.options.logger.error(e))}};get state(){return this.#e}constructor(e){this.options=e;let t=o.Router();t.use(async(e,t,n)=>{let r=await J(this.#e);if(!r||r.kind===`error`)return n();try{r.viteServer.middlewares(e,t,n)}catch(e){this.options.logger.error(`Vite middleware error: ${e}`),t.status(500).end(`Vite middleware error: ${e}`)}}),this.middleware=t,this.#t=p()}async loadIndexHtml(e,n){return this.#t(async()=>{try{let r=await J(this.#e);if(!r)return N(`Vite server is not running`);if(r.kind===`error`)return N(r.error);let i=await c.readFile(this.options.shadowHtmlFilePath,`utf-8`),{config:a,viteServer:o}=r,{filePath:s,name:l}=t(n),d=s.replace(/\\/g,`/`),f=a.wrapper,p=f&&await c.pathExists(u.join(this.options.rootDir,f.path))?f.path.replace(/\\/g,`/`):null;return await o.transformIndexHtml(e,i.replace(`<!-- %OPTIONAL_HEAD_CONTENT% -->`,`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(JSON.stringify({previewablePath:d,previewableName:l,wrapperPath:p,wrapperName:f?.componentName||null,detectedGlobalCssFilePaths:a.detectedGlobalCssFilePaths}),`utf8`).toString(`base64url`)}"><\/script>`))}catch(e){return N(`${e}`)}})}async start(){let e;this.#e={kind:`starting`,promise:new Promise(t=>{e=e=>{this.#e=e,t(e)}})},this.options.reader.listeners.add(this.#n);try{process.chdir(this.options.rootDir);let t=await fe(this.options.rootDir,Z(this.options.logger)),n=await E(this.options.rootDir,`**/@(${K.join(`|`)}).@(${q.join(`|`)})`,{maxDepth:3}),r={...t,wrapper:t.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:n.map(e=>u.relative(this.options.rootDir,e))},i=[],a=null;for(let e of[`tsconfig.json`,`jsconfig.json`]){let t=u.join(this.options.rootDir,e);try{if(await c.pathExists(t)){let e=S(t)||null;if(e){a=Ae.parse(e);break}}}catch(e){this.options.logger.warn(`Unable to load tsconfig from ${t}: ${e}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(a||null,null,2)}`);let o=a?.compilerOptions?.baseUrl||``,s=a?.compilerOptions?.paths||{},l=o.startsWith(`./`)?o.substring(1):o;l&&!l.endsWith(`/`)&&(l+=`/`);for(let[e,t]of Object.entries(s)){let n=t[0];if(!n)continue;let r=e.endsWith(`/*`)?e.slice(0,e.length-2):e,a=n.endsWith(`/*`)?n.slice(0,n.length-2):n;i.push({find:r,replacement:u.join(this.options.rootDir,o,a)})}let d=await C.loadConfigFromFile({command:`serve`,mode:`development`},void 0,this.options.rootDir),f=C.createLogger(Z(this.options.logger)),p=this.options.frameworkPlugin.viteConfig(await X([...d?.config.plugins||[],...r.vite?.plugins||[]])),m=r.vite?.publicDir||d?.config.publicDir||p.publicDir||r.publicDir||`public`,h=Q(this.options.reader,await X([x({root:this.options.rootDir}),be(),Ce({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:[...r.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[te(this.options.rootDir)],u.dirname(G(`@cfp-studio/fiber-reader`))],moduleGraph:()=>this.#e?.kind===`running`?this.#e.viteServer.moduleGraph:null,esbuildOptions:p.esbuild||{}}),ye(),ve(),L({readFile:e=>this.options.reader.read(e).then(e=>e?.kind===`file`?e.read():null)}),he(),Se({rootDir:this.options.rootDir,publicDir:m}),p.plugins]));this.options.logger.debug(`Creating Vite server`);let g=await C.createServer({...p,...d?.config,...r.vite,configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,hmr:{overlay:!1,server:this.options.server,clientPort:this.options.clientPort||this.options.port,...typeof r.vite?.server?.hmr==`object`?r.vite?.server?.hmr:{}},fs:{strict:!1,...r.vite?.server?.fs||{}},...r.vite?.server},customLogger:{info:f.info,warn:f.warn,error:(e,t)=>{e.startsWith(`\x1B[31mInternal server error`)||this.#e?.kind===`running`&&this.#e.viteServer.ws.send({type:`error`,err:{message:e,stack:``}}),f.error(e,t)},warnOnce:f.warnOnce,clearScreen:()=>{},hasWarned:f.hasWarned,hasErrorLogged:f.hasErrorLogged},clearScreen:!1,cacheDir:r.vite?.cacheDir||d?.config.cacheDir||this.options.cacheDir,publicDir:m,plugins:h,define:{__filename:void 0,__dirname:void 0,process:void 0,...p.define,...d?.config.define,...r.vite?.define},resolve:{...d?.config.resolve,...r.vite?.resolve,alias:[{find:`@cfp-studio/fiber-reader`,replacement:G(`@cfp-studio/fiber-reader`)},...Y(r.vite?.resolve?.alias),...Y(r.alias),...Y(d?.config.resolve?.alias),...i,{find:/^~(.*)/,replacement:`${l}$1`},{find:`@`,replacement:l},...Y(p.resolve?.alias)]}});e({kind:`running`,config:r,viteServer:g}),this.options.logger.debug(`Done starting Vite server`)}catch(t){this.options.logger.error(`Vite startup error: ${t}`),e({kind:`error`,error:t.stack||t.message})}return this.#e.promise}async stop({restart:e}={restart:!1}){await this.#t(async()=>{this.options.reader.listeners.remove(this.#n);let t=await J(this.#e);return t?.kind===`running`&&await t.viteServer.close(),e?this.start():this.#e=null})}async onFileChanged(e,t){let n=await J(this.state);if(!n)return;if(!t.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(u.relative(this.options.rootDir,e)),Oe.has(u.basename(e)))){this.options.logger.info(`检测到依赖变化. 重启服务...`),await this.stop({restart:!0});return}if(n.kind!==`running`)return;let{viteServer:r,config:i}=n;if(t.virtual){let t=await r.moduleGraph.getModulesByFile(z(e));for(let e of t||[])if(e.id)try{let t=await r.pluginContainer.load(e.id);if(!t)continue;let n=typeof t==`object`?t.code:t;await r.pluginContainer.transform(n,e.id)}catch{return}for(let t of r.watcher.listeners(`change`))t(e)}else i.wrapper&&e===u.resolve(this.options.rootDir,i.wrapper.path)&&(r.moduleGraph.invalidateAll(),r.ws.send({type:`full-reload`}))}};function Y(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({find:e,replacement:t})):[]}async function X(e){let t=[];for(let n of await Promise.all(e))n&&(Array.isArray(n)?t.push(...await X(n)):t.push(n));return t}function Z(e){switch(e.level){case`fatal`:return`silent`;case`error`:return`error`;case`warn`:return`warn`;case`info`:return`info`;case`debug`:return`info`;case`trace`:return`info`;case`silent`:return`silent`;default:return e.warn(`Unknown log level: ${e.level}`),`info`}}function Q(e,t){return t.map(async t=>{if(!t.handleHotUpdate)return t;let n=typeof t.handleHotUpdate==`function`?t.handleHotUpdate:t.handleHotUpdate.handler;return{...t,handleHotUpdate:async t=>{await n({...t,read:async()=>{let n=await e.read(t.file);return n?.kind===`file`?n.read():t.read()}})}}})}const Ae=w.object({compilerOptions:w.object({baseUrl:w.string().optional(),paths:w.record(w.array(w.string())).optional()}).optional()});var je=class{constructor(e){this.options=e,this.viteManager=null,this.status={kind:`stopped`},this.disposeObserver=null,this.transformingReader=a([e.reader,i({mapping:{from:e.frameworkPlugin.previewDirPath,to:u.join(e.rootDir,`__previewjs_internal__`,`renderer`)},watch:!1}),i({mapping:{from:e.previewDirPath,to:e.rootDir},watch:!1})])}async start(){let e=this.status;switch(e.kind){case`starting`:try{await e.promise}catch(e){this.options.logger.error(e),this.status={kind:`stopped`},await this.startFromStopped()}break;case`started`:break;case`stopping`:try{await e.promise}catch(e){this.options.logger.error(e),this.status={kind:`stopped`}}await this.start();break;case`stopped`:await this.startFromStopped();break;default:throw y(e)}}async startFromStopped(){this.status={kind:`starting`,promise:(async()=>{let e=o.Router();if(e.use((e,t,n)=>{t.setHeader(`Cache-Control`,`max-age=0, must-revalidate`),n()}),e.use(this.options.middlewares),e.get(/^\/.*:[^/]+\/$/,async(e,t,n)=>{let r=e.header(`Accept`);if(e.url.includes(`?html-proxy`)){n();return}if(r===`text/x-vite-ping`){t.writeHead(204).end();return}let i=e.path.substring(1,e.path.length-1);if(!this.viteManager){t.status(404).end(`Vite服务器未启动`);return}t.status(200).set({"Content-Type":`text/html`}).end(await this.viteManager.loadIndexHtml(e.originalUrl,i))}),e.use(`/ping`,async(e,t)=>{t.json(JSON.stringify({pong:`match!`}))}),e.use((e,t,n)=>{this.viteManager?.middleware(e,t,n)}),this.transformingReader.observe)try{this.disposeObserver=await this.transformingReader.observe(this.options.rootDir)}catch(e){this.options.logger.error(e,`启动文件系统监听失败:`)}let{server:t,disposeHttpServer:n}=await this.options.getHttpServer(e);ae(this.options.rootDir)&&this.options.logger.debug(`已清理旧缓存目录 node_modules/.previewjs`),this.options.logger.debug(`启动 Vite manager ...`),this.viteManager=new ke({rootDir:this.options.rootDir,shadowHtmlFilePath:u.join(this.options.previewDirPath,`index.html`),reader:this.transformingReader,cacheDir:u.join(T(this.options.rootDir),`vite`),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:t,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug(`预览服务已就绪`),this.status={kind:`started`,onStop:n}})()},await this.status.promise;for(let e=0;;e++)try{await b.get(`http://localhost:${this.options.port}`);break}catch(t){if(e===10)throw t;await new Promise(e=>setTimeout(e,50))}}async stop(){if(this.status.kind===`starting`)try{await this.status.promise}catch{this.status={kind:`stopped`}}if(this.status.kind!==`started`)return;let e=this.status.onStop;this.status={kind:`stopping`,promise:(async()=>{await this.disposeObserver?.(),this.disposeObserver=null,await this.viteManager?.stop(),this.viteManager=null,await e(),this.status={kind:`stopped`}})()},await this.status.promise}},Me=class{constructor(e){this.logger=e,this.handlers=new Map,this.registerRPC=(e,t)=>{if(this.handlers.has(e.path))throw Error(`端点 '${e.path}' 已经注册了 handler,是否重复注册?`);this.handlers.set(e.path,t)}}async handle(e,t){let n=this.handlers.get(e);if(!n)return{kind:`error`,message:`路径 '${e}' 没有注册对应的 handler`};this.logger.debug(`RPC ${e} invoked`);try{return{kind:`success`,response:await n(t)}}catch(t){return this.logger.error(`RPC ${e} failed: ${t}`),t instanceof Error?{kind:`error`,message:t.message}:{kind:`error`,message:`${t}`}}}};function $(){return process.env.CFP_BRAND_NAME||`CFP Studio`}async function Ne(e,t,n){let r=await j(e,t);for(let e of n)if(e.info&&await e.isCompatible(r))return e.info?.name;return null}const{pino:Pe}=d,Fe=f,Ie=e(import.meta.url);process.on(`uncaughtException`,e=>{console.error(`Core 遇到未捕获的异常`,e)}),process.on(`unhandledRejection`,e=>{console.error(`Core 遇到未处理的 Promise 对象`,e)});async function Le({rootDir:e,frameworkPlugin:a,logger:c=Pe({level:process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase()||`warn`},Fe({colorize:!0})),reader:d=i(),onServerStart:f=()=>Promise.resolve({})}){if(!a.info)throw Error(`framework plugin 与当前版本 ${$()} 不兼容. 请升级.`);if(a.info.apiVersion>5)throw Error(` ${a.info.name} 的 API 版本是 ${a.info.apiVersion}. 高于当前安装的 ${$()}, 请升级至最新版本.`);let p=await j(c,e);if(!await a.isCompatible(p))throw Error(` ${a.info.name} 与当前工作区的前端框架版本不兼容。`);c.info(`使用 ${a.info.name} 在目录: ${e} 中创建工作区`);let m=await a.create({rootDir:e,reader:d,logger:c,dependencies:p}),h=new Set,g={frameworkPluginName:a.info.name,crawlFiles:m.crawlFiles,typeAnalyzer:m.typeAnalyzer,rootDir:e,reader:d,startServer:async({asMiddleware:i,port:p,clientPort:_,onStop:v}={})=>{let y=p||await ce(3140),b=new Me(c);b.registerRPC(n.Analyze,async({previewableIds:n})=>{c.debug(`分析: ${n.join(`, `)}`);let i=await m.crawlFiles([...new Set(n.map(n=>u.join(e,t(n).filePath)))]);c.debug(`检测到 ${i.components.length} 个组件和 ${i.stories.length} 个story`);let a=[],o=Object.fromEntries(i.components.map(e=>[e.id,e])),s=Object.fromEntries(i.stories.map(e=>[e.id,e])),l={};for(let e of n){let n=o[e],i=s[e],u;if(n){let t;c.debug(`分析组件: ${e}`),{props:t,types:u}=await n.analyze(),a.push({kind:`component`,id:e,exported:n.exported,sourcePosition:n.sourcePosition,props:t})}else if(i){let t;i.associatedComponent?({props:t,types:u}=await i.associatedComponent.analyze(),c.debug(`分析 story: ${e} 的关联组件`)):(c.debug(`story: ${e} 没有关联的组件`),t=r,u={});let n=null;({args:n}=await i.analyze()),a.push({kind:`story`,id:e,sourcePosition:i.sourcePosition,associatedComponentId:i.associatedComponent?.id||null,props:t,args:n}),c.debug(`story args: ${JSON.stringify(n)}`)}else{let{filePath:n,name:r}=t(e);throw Error(`在 ${n} 中未找到组件 ${r}. `)}l={...l,...u}}return{previewables:a,types:l}}),b.registerRPC(n.GetInfo,async()=>({frameworkPlugin:a.info})),b.registerRPC(n.CrawlFiles,e=>se(c,g,m,e));let x=[s(),o.json(),async(e,t,n)=>{e.path.startsWith(`/api/`)?t.json(await b.handle(e.path.substr(5),e.body)):n()}];if(f){let{middlewares:e=[]}=await f({registerRPC:(e,t)=>b.registerRPC(e,t),workspace:g});x.push(...e)}let S=i?async e=>{let t=i.register(e);return{server:i.server,disposeHttpServer:async()=>{t()}}}:async e=>{c.debug(`启动 Express 服务器`);let t=o();t.use(e);let n=await new Promise(e=>{let n=t.listen(y,()=>{c.info(`${$()} 预览服务运行在 http://localhost:${y}.`),e(n)})}),r=l({server:n,gracefulTerminationTimeout:0});return{server:n,disposeHttpServer:async()=>{await r.terminate(),c.info(`${$()} 预览服务器已停止.`)}}},C=new je({reader:d,rootDir:e,previewDirPath:u.join(u.dirname(u.dirname(Ie.resolve(`@cfp-studio/iframe`))),`preview`),frameworkPlugin:m,logger:c,middlewares:x,getHttpServer:S,port:y,clientPort:_});return await C.start(),h.add(C),{port:y,stop:async()=>{h.delete(C),await C.stop(),await v?.()}}},dispose:async()=>{await Promise.all([...h].map(e=>e.stop())),h.clear(),m.dispose()}};return g}function Re(e){let t=u.resolve(e);for(;t!==u.dirname(t);){if(c.existsSync(u.join(t,`package.json`)))return t;t=u.dirname(t)}return null}export{Le as createWorkspace,Ne as findCompatiblePlugin,Re as findWorkspaceRoot,z as toVitePath};
package/package.json CHANGED
@@ -1,25 +1,17 @@
1
1
  {
2
2
  "name": "@cfp-studio/core",
3
- "version": "1.0.3",
3
+ "version": "1.0.6",
4
4
  "license": "MIT",
5
- "type": "module",
6
- "main": "./dist/index.mjs",
7
- "types": "./dist/index.d.ts",
8
5
  "files": [
9
6
  "dist"
10
7
  ],
8
+ "type": "module",
9
+ "main": "./dist/index.mjs",
10
+ "types": "./dist/index.d.mts",
11
11
  "dependencies": {
12
- "@cfp-studio/analyzer-api": "^0.1.12",
13
- "@cfp-studio/api": "^16.1.1",
14
- "@cfp-studio/config": "7.0.1",
15
- "@cfp-studio/iframe": "^18.0.1",
16
- "@cfp-studio/middleware": "2.1.100",
17
- "@cfp-studio/serializable-values": "^9.0.7",
18
- "@cfp-studio/type-analyzer": "^10.1.8",
19
- "@cfp-studio/vfs": "^2.1.6",
20
- "@fwouts/vite-tsconfig-paths": "^4.2.1",
12
+ "@fwouts/vite-tsconfig-paths": "4.2.1",
21
13
  "assert-never": "1.4.0",
22
- "axios": "1.12.2",
14
+ "axios": "1.20.0",
23
15
  "cors": "2.8.5",
24
16
  "exclusive-promises": "1.0.3",
25
17
  "express": "5.1.0",
@@ -29,12 +21,16 @@
29
21
  "http-terminator": "3.2.0",
30
22
  "pino": "9.11.0",
31
23
  "pino-pretty": "13.1.1",
32
- "rollup-plugin-friendly-type-imports": "1.0.3",
33
- "ts-node": "10.9.2",
34
24
  "tsconfig-paths": "4.2.0",
35
- "typescript": "5.9.2",
36
- "vite": "6.2.0",
37
- "zod": "3.24.1"
25
+ "typescript": "5.9.3",
26
+ "vite": "6.4.5",
27
+ "zod": "3.24.1",
28
+ "@cfp-studio/fiber-reader": "0.1.0",
29
+ "@cfp-studio/analyzer-api": "0.1.12",
30
+ "@cfp-studio/iframe": "18.2.0",
31
+ "@cfp-studio/type-analyzer": "10.1.8",
32
+ "@cfp-studio/api": "16.1.1",
33
+ "@cfp-studio/vfs": "2.1.6"
38
34
  },
39
35
  "devDependencies": {
40
36
  "@rollup/plugin-alias": "5.1.1",
@@ -42,14 +38,15 @@
42
38
  "@types/express": "4.17.21",
43
39
  "@types/fs-extra": "11.0.4",
44
40
  "@types/html-escaper": "3.0.4",
45
- "shx": "0.3.4",
46
- "unbuild": "2.0.0",
47
- "vitest": "2.1.9"
41
+ "vitest": "5.0.5"
48
42
  },
49
43
  "scripts": {
50
44
  "prepublish": "pnpm release",
51
- "build": "tsc && unbuild",
52
- "release": "tsc && unbuild --minify",
53
- "test": "vitest"
45
+ "build": "tsdown",
46
+ "typecheck": "tsc --noEmit",
47
+ "release": "tsdown --minify",
48
+ "test": "vitest",
49
+ "lint": "oxlint",
50
+ "format": "oxfmt --write ."
54
51
  }
55
52
  }
package/dist/index.d.ts DELETED
@@ -1,218 +0,0 @@
1
- import { Analyzer } from '@cfp-studio/analyzer-api';
2
- import { TypeAnalyzer } from '@cfp-studio/type-analyzer';
3
- import { Reader } from '@cfp-studio/vfs';
4
- import * as express from 'express';
5
- import express__default from 'express';
6
- import http from 'node:http';
7
- import { Logger } from 'pino';
8
- import { FrameworkPluginInfo, RPC, RequestOf, ResponseOf } from '@cfp-studio/api';
9
- import * as vite from 'vite';
10
-
11
- /**
12
- * 定义包依赖项的类型,它是一个记录类型,键为包名,值为包含主要版本号和读取已安装版本方法的对象
13
- * @typedef {Object} PackageDependencies
14
- * @property {number} majorVersion - 包的主要版本号(已弃用)
15
- * @property {function} readInstalledVersion - 异步读取已安装包版本的函数,返回一个 Promise,解析为字符串或 null
16
- */
17
- type PackageDependencies = Record<string, {
18
- /** @deprecated */
19
- majorVersion: number;
20
- /**
21
- * 异步读取已安装包的版本号
22
- * @returns {Promise<string | null>} - 一个 Promise,解析为已安装包的版本号字符串,如果读取失败则为 null
23
- */
24
- readInstalledVersion(): Promise<string | null>;
25
- }>;
26
-
27
- /**
28
- * 定义框架插件工厂的接口。
29
- * 该工厂用于创建框架插件实例,并提供检查兼容性的方法。
30
- */
31
- interface FrameworkPluginFactory {
32
- /**
33
- * 框架插件的信息,包含插件的基本描述和元数据。
34
- */
35
- info: FrameworkPluginInfo;
36
- /**
37
- * 检查当前项目的依赖是否与该框架插件兼容。
38
- *
39
- * @param dependencies - 项目的依赖包信息。
40
- * @returns 一个 Promise,解析为布尔值,表示是否兼容。
41
- */
42
- isCompatible(dependencies: PackageDependencies): Promise<boolean>;
43
- /**
44
- * 创建框架插件实例。
45
- *
46
- * @param options - 创建插件所需的选项。
47
- * @param options.rootDir - 项目的根目录。
48
- * @param options.reader - 用于读取文件的读取器。
49
- * @param options.logger - 日志记录器,用于记录插件运行时的信息。
50
- * @param options.dependencies - 项目的依赖包信息。
51
- * @returns 一个 Promise,解析为创建的框架插件实例。
52
- */
53
- create(options: {
54
- rootDir: string;
55
- reader: Reader;
56
- logger: Logger;
57
- dependencies: PackageDependencies;
58
- }): Promise<FrameworkPlugin>;
59
- }
60
- /**
61
- * 定义框架插件的接口。
62
- * 该插件继承自 Analyzer 接口,并提供了一些额外的配置和方法。
63
- */
64
- interface FrameworkPlugin extends Analyzer {
65
- /**
66
- * 默认包装器的文件路径。
67
- */
68
- defaultWrapperPath: string;
69
- /**
70
- * 预览目录的文件路径。
71
- */
72
- previewDirPath: string;
73
- /**
74
- * 生成 Vite 配置的函数。
75
- *
76
- * @param configuredPlugins - 已配置的 Vite 插件列表。
77
- * @returns Vite 用户配置对象。
78
- */
79
- viteConfig: (configuredPlugins: vite.Plugin[]) => vite.UserConfig;
80
- /**
81
- * 清理插件资源的方法。
82
- * 当插件不再使用时,调用此方法释放资源。
83
- */
84
- dispose(): void;
85
- }
86
-
87
- /**
88
- * 定义注册 RPC 端点的函数类型。
89
- * @template E - RPC 端点的类型。
90
- * @param endpoint - RPC 端点对象。
91
- * @param handler - 处理该端点请求的函数。
92
- */
93
- type RegisterRPC = <E extends RPC<any, any>>(endpoint: E, handler: RequestHandler<RequestOf<E>, ResponseOf<E>>) => void;
94
- /**
95
- * 定义请求处理函数的类型。
96
- * @template Req - 请求数据的类型。
97
- * @template Res - 响应数据的类型。
98
- * @param request - 请求的数据。
99
- * @returns 包含响应结果的 Promise。
100
- */
101
- type RequestHandler<Req, Res> = (request: Req) => Promise<Res>;
102
-
103
- /**
104
- * 定义 OnServerStart 类型,这是一个异步函数类型,用于在服务器启动时执行特定操作
105
- * @param options - 包含服务器启动所需的选项
106
- * @param options.versionCode - 可选的版本代码
107
- * @param options.registerRPC - 用于注册远程过程调用的函数
108
- * @param options.workspace - 当前的工作区对象
109
- * @returns 返回一个 Promise,该 Promise 解析为一个包含中间件数组的对象
110
- */
111
- type OnServerStart = (options: {
112
- /**
113
- * 可选的版本代码
114
- */
115
- versionCode?: string;
116
- /**
117
- * 用于注册远程过程调用的函数
118
- */
119
- registerRPC: RegisterRPC;
120
- /**
121
- * 当前的工作区对象
122
- */
123
- workspace: Workspace;
124
- }) => Promise<{
125
- /**
126
- * 可选的 express 请求处理中间件数组
127
- */
128
- middlewares?: express.RequestHandler[];
129
- }>;
130
-
131
- /**
132
- * 查找与项目依赖兼容的框架插件
133
- * @param logger - 用于日志记录的 Logger 实例
134
- * @param rootDir - 项目的根目录路径
135
- * @param frameworkPlugins - 框架插件工厂数组
136
- * @returns 兼容插件的名称,如果未找到则返回 null
137
- */
138
- declare function findCompatiblePlugin(logger: Logger, rootDir: string, frameworkPlugins: FrameworkPluginFactory[]): Promise<string>;
139
-
140
- declare function toVitePath(absoluteFilePath: string): string;
141
-
142
- /**
143
- * 创建一个新的工作区实例。
144
- *
145
- * 该方法用于初始化一个工作区,包括加载框架插件、分析项目依赖、创建预览服务器等。
146
- *
147
- * @param options 配置选项
148
- * @param options.rootDir 项目根目录路径
149
- * @param options.frameworkPlugin 框架插件工厂函数
150
- * @param options.logger 日志记录器,默认为 Pino 实例
151
- * @param options.reader 文件读取器,默认为文件系统读取器
152
- * @param options.onServerStart 服务器启动时的回调函数
153
- * @returns Workspace 返回一个工作区实例
154
- */
155
- declare function createWorkspace({ rootDir, frameworkPlugin: frameworkPluginFactory, logger, reader, onServerStart, }: {
156
- rootDir: string;
157
- frameworkPlugin: FrameworkPluginFactory;
158
- logger?: Logger;
159
- reader?: Reader;
160
- onServerStart?: OnServerStart;
161
- }): Promise<Workspace>;
162
- /**
163
- * 查找包含 package.json 的最近祖先目录路径。
164
- *
165
- * 该方法从指定文件路径开始,逐级向上查找,直到找到包含 package.json 的目录。
166
- *
167
- * @param absoluteFilePath 文件的绝对路径
168
- * @returns 返回包含 package.json 的目录路径,如果未找到则返回 null
169
- */
170
- declare function findWorkspaceRoot(absoluteFilePath: string): string | null;
171
- /**
172
- * 工作区接口定义。
173
- *
174
- * 该接口描述了一个工作区,包含项目根目录、文件读取器、框架插件名称、类型分析器等属性。
175
- *
176
- * @property rootDir 项目根目录路径
177
- * @property reader 文件读取器
178
- * @property frameworkPluginName 框架插件名称
179
- * @property typeAnalyzer 类型分析器实例
180
- * @property crawlFiles 文件分析函数
181
- * @property startServer 启动预览服务器函数
182
- * @property dispose 清理工作区资源函数
183
- */
184
- interface Workspace {
185
- rootDir: string;
186
- reader: Reader;
187
- frameworkPluginName: string;
188
- typeAnalyzer: Omit<TypeAnalyzer, "dispose">;
189
- crawlFiles: Analyzer["crawlFiles"];
190
- startServer: (options?: {
191
- port?: number;
192
- clientPort?: number;
193
- onStop?: () => void;
194
- } & ({
195
- asMiddleware?: never;
196
- } | {
197
- asMiddleware: {
198
- server: http.Server;
199
- register: (handler: express__default.RequestHandler) => () => void;
200
- };
201
- port: number;
202
- })) => Promise<PreviewServer>;
203
- dispose(): Promise<void>;
204
- }
205
- /**
206
- * 预览服务器接口定义。
207
- *
208
- * 该接口描述了一个预览服务器,包含端口号和停止函数。
209
- *
210
- * @property port 预览服务器端口号
211
- * @property stop 停止预览服务器函数
212
- */
213
- interface PreviewServer {
214
- port: number;
215
- stop(): Promise<void>;
216
- }
217
-
218
- export { type FrameworkPlugin, type FrameworkPluginFactory, type OnServerStart, type PackageDependencies, type PreviewServer, type Workspace, createWorkspace, findCompatiblePlugin, findWorkspaceRoot, toVitePath };