@cfp-studio/core 1.0.11 → 1.0.13
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/dist/index.d.mts +80 -3
- package/dist/index.mjs +6 -6
- package/package.json +59 -59
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,40 @@
|
|
|
1
1
|
import { Analyzer } from "@cfp-studio/analyzer-api";
|
|
2
|
-
import { FrameworkPluginInfo, RPC, RPCs, RequestOf, ResponseOf } from "@cfp-studio/api";
|
|
2
|
+
import { FrameworkPluginInfo, Logger, RPC, RPCs, RequestOf, ResponseOf } from "@cfp-studio/api";
|
|
3
3
|
import { TypeAnalyzer } from "@cfp-studio/type-analyzer";
|
|
4
4
|
import { Reader } from "@cfp-studio/vfs";
|
|
5
5
|
import * as express$1 from "express";
|
|
6
6
|
import express from "express";
|
|
7
|
-
import { Logger } from "pino";
|
|
8
7
|
import * as vite from "vite";
|
|
9
8
|
import http from "node:http";
|
|
10
9
|
|
|
10
|
+
//#region src/caching.d.ts
|
|
11
|
+
/**
|
|
12
|
+
* 扫描缓存的「自省」结果(诊断用,不改任何状态)。
|
|
13
|
+
*
|
|
14
|
+
* 为什么需要:缓存只按**文件 mtime** 决定要不要重新分析(见 `crawl-files.ts`)。
|
|
15
|
+
* 一旦某次扫描产出了错误结果(比如分析器有 bug 时记录了零组件),
|
|
16
|
+
* 它会一直命中,**即使那个 bug 已经修好** —— 源码没改过,mtime 永远旧于缓存里的
|
|
17
|
+
* `detectionStartTimestamp`。用户看到的现象是「升级了还是扫不出组件」,
|
|
18
|
+
* 而所有日志都是干净的。
|
|
19
|
+
*
|
|
20
|
+
* 2026-11-06 实测:`type-analyzer` 修好 `.d.ts` 解析后,preact 工程仍然零组件,
|
|
21
|
+
* 必须手动 `rm -rf node_modules/.cfp` 才恢复。这跟 `docs/todo/41`
|
|
22
|
+
* (`.gitignore` 双向失效)是同一类病。
|
|
23
|
+
*/
|
|
24
|
+
type ScanCacheInspection = {
|
|
25
|
+
/** 缓存目录的绝对路径(即使不存在也给出来,方便用户自己删)。 */cacheDir: string; /** `components.json` 是否存在。 */
|
|
26
|
+
exists: boolean; /** 缓存里记录的分析起始时间;无缓存时为 `null`。 */
|
|
27
|
+
detectionStartTimestamp: number | null; /** 缓存里记录的组件数 / story 数。 */
|
|
28
|
+
cachedComponents: number;
|
|
29
|
+
cachedStories: number;
|
|
30
|
+
/**
|
|
31
|
+
* 有多少源文件的 mtime **早于**缓存时间戳 —— 这些文件下次扫描时会被跳过。
|
|
32
|
+
* 数字很大而缓存里组件是 0,几乎可以断定「一份错的空缓存把扫描钉死了」。
|
|
33
|
+
*/
|
|
34
|
+
skippedSourceFiles: number; /** 参与统计的源文件总数(`*.{js,jsx,ts,tsx,svelte,vue}`)。 */
|
|
35
|
+
sourceFiles: number;
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
11
38
|
//#region src/plugins/dependencies.d.ts
|
|
12
39
|
/**
|
|
13
40
|
* 定义包依赖项的类型,它是一个记录类型,键为包名,值为包含主要版本号和读取已安装版本方法的对象
|
|
@@ -23,6 +50,13 @@ type PackageDependencies = Record<string, {
|
|
|
23
50
|
*/
|
|
24
51
|
readInstalledVersion(): Promise<string | null>;
|
|
25
52
|
}>;
|
|
53
|
+
/**
|
|
54
|
+
* 从指定根目录下的 package.json 文件中提取所有依赖项的信息
|
|
55
|
+
* @param {Logger} logger - 用于记录错误信息的日志记录器
|
|
56
|
+
* @param {string} rootDir - 项目的根目录路径
|
|
57
|
+
* @returns {Promise<PackageDependencies>} - 一个 Promise,解析为包含所有依赖项信息的对象
|
|
58
|
+
*/
|
|
59
|
+
declare function extractPackageDependencies(logger: Logger, rootDir: string): Promise<PackageDependencies>;
|
|
26
60
|
//#endregion
|
|
27
61
|
//#region src/plugins/framework.d.ts
|
|
28
62
|
/**
|
|
@@ -157,6 +191,31 @@ type OnServerStart = (options: {
|
|
|
157
191
|
* @returns 兼容插件的名称,如果未找到则返回 null
|
|
158
192
|
*/
|
|
159
193
|
declare function findCompatiblePlugin(logger: Logger, rootDir: string, frameworkPlugins: FrameworkPluginFactory[]): Promise<string>;
|
|
194
|
+
/** 单个插件的判定结果。 */
|
|
195
|
+
type CompatibilityProbe = {
|
|
196
|
+
name: string;
|
|
197
|
+
compatible: boolean; /** `isCompatible` 抛出的异常(通常它自己会吞掉并返回 false,这里是兜底)。 */
|
|
198
|
+
error: string | null;
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* 与 {@link findCompatiblePlugin} 相同的判定,但**把每个插件的结果都带出来**。
|
|
202
|
+
*
|
|
203
|
+
* ## 为什么需要它
|
|
204
|
+
*
|
|
205
|
+
* `findCompatiblePlugin` 只返回第一个兼容的名字(或 `null`)。失败时调用方只知道
|
|
206
|
+
* 「没有工作区」,而真正的原因可能是:
|
|
207
|
+
*
|
|
208
|
+
* 1. 工程声明了框架依赖,但 `node_modules` 没装好(`readInstalledVersion` 失败);
|
|
209
|
+
* 2. 装了,但 pnpm 严格模式下解析不到(`docs/todo/42` 那类);
|
|
210
|
+
* 3. 框架插件压根没被 `loadModules()` 加载(2026-11-06 修过一次);
|
|
211
|
+
* 4. 这确实不是受支持的框架。
|
|
212
|
+
*
|
|
213
|
+
* 四种情况的修法完全不同,而在日志里长得一模一样 —— 2026-11-06 排查 preact
|
|
214
|
+
* 扫不出组件时,最耗时的就是分不清属于哪一种。所以把判定明细亮出来。
|
|
215
|
+
*
|
|
216
|
+
* **只读**:不创建/缓存工作区。诊断端点与日志都用它。
|
|
217
|
+
*/
|
|
218
|
+
declare function probeFrameworkCompatibility(logger: Logger, rootDir: string, frameworkPlugins: FrameworkPluginFactory[]): Promise<CompatibilityProbe[]>;
|
|
160
219
|
//#endregion
|
|
161
220
|
//#region src/vite/vite-paths.d.ts
|
|
162
221
|
declare function toVitePath(absoluteFilePath: string): string;
|
|
@@ -214,6 +273,14 @@ interface Workspace {
|
|
|
214
273
|
rootDir: string;
|
|
215
274
|
reader: Reader;
|
|
216
275
|
frameworkPluginName: string;
|
|
276
|
+
/**
|
|
277
|
+
* 框架插件自身的包版本(`FrameworkPluginInfo.version`)。
|
|
278
|
+
*
|
|
279
|
+
* 用途:组件扫描缓存的目录名(`getScanCacheDir`)。插件升级后旧的空/错误
|
|
280
|
+
* 扫描结果不能继续被复用 —— 见 `caching.ts` 的 `getAnalysisFingerprint`。
|
|
281
|
+
* 旧插件不声明时为 `undefined`,退化成 `unknown`。
|
|
282
|
+
*/
|
|
283
|
+
frameworkPluginVersion?: string;
|
|
217
284
|
typeAnalyzer: Omit<TypeAnalyzer, "dispose">;
|
|
218
285
|
/**
|
|
219
286
|
* 分析**指定的**文件列表(`Analyzer` 层)。
|
|
@@ -238,6 +305,16 @@ interface Workspace {
|
|
|
238
305
|
* 由 Diagnostics 视图在用户主动触发时调。见 `findGitignoredSourceFiles()` 的长注释。
|
|
239
306
|
*/
|
|
240
307
|
findGitignoredSourceFiles: () => Promise<string[]>;
|
|
308
|
+
/**
|
|
309
|
+
* 检查**组件扫描缓存**的状态(只读,诊断用)。
|
|
310
|
+
*
|
|
311
|
+
* 回答的是「是不是一份过期的缓存把扫描钉住了」—— 缓存只按文件 mtime 判定
|
|
312
|
+
* 要不要重新分析,于是一旦某次分析在 bug 下产出了零组件,修好 bug 也恢复不了
|
|
313
|
+
* (见 `caching.ts` 的 `ScanCacheInspection`)。
|
|
314
|
+
*/
|
|
315
|
+
inspectScanCache: () => Promise<ScanCacheInspection>;
|
|
316
|
+
/** 删除组件扫描缓存(诊断的「一键修」用)。返回是否真的删掉了。 */
|
|
317
|
+
clearScanCache: () => boolean;
|
|
241
318
|
startServer: (options?: {
|
|
242
319
|
port?: number;
|
|
243
320
|
clientPort?: number;
|
|
@@ -266,4 +343,4 @@ interface PreviewServer {
|
|
|
266
343
|
stop(): Promise<void>;
|
|
267
344
|
}
|
|
268
345
|
//#endregion
|
|
269
|
-
export { type FrameworkPlugin, type FrameworkPluginFactory, type OnServerStart, type PackageDependencies, PreviewServer, Workspace, createWorkspace, findCompatiblePlugin, findWorkspaceRoot, toVitePath };
|
|
346
|
+
export { type CompatibilityProbe, type FrameworkPlugin, type FrameworkPluginFactory, type OnServerStart, type PackageDependencies, PreviewServer, Workspace, createWorkspace, extractPackageDependencies, findCompatiblePlugin, findWorkspaceRoot, probeFrameworkCompatibility, toVitePath };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import t from"node:path";import{decodePreviewableId as
|
|
2
|
-
- `)}`);let s=await r.crawlFiles(i);e.debug(`组件检测完成`);for(let e of s.components)a.push({id:e.id,sourcePosition:e.sourcePosition,exported:e.exported});for(let e of s.stories)o.push({id:e.id,sourcePosition:e.sourcePosition,associatedComponentId:e.associatedComponent?.id||null});return{components:a,stories:o}}async function
|
|
1
|
+
import{createRequire as e}from"node:module";import t from"node:path";import{createPipelineLogger as n,decodePreviewableId as r}from"@cfp-studio/analyzer-api";import{RPCs as i}from"@cfp-studio/api";import{UNKNOWN_TYPE as a}from"@cfp-studio/type-analyzer";import{createFileSystemReader as o,createStackedReader as s}from"@cfp-studio/vfs";import c from"cors";import l from"express";import u from"fs-extra";import{createHttpTerminator as d}from"http-terminator";import f from"node:fs";import p,{fileURLToPath as m,pathToFileURL as h}from"node:url";import{exclusivePromiseRunner as g}from"exclusive-promises";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 T(){return process.env.CFP_BRAND_NAME||`CFP Studio`}function ie(){let e=p.fileURLToPath(new URL(`.`,import.meta.url)),{version:n}=JSON.parse(f.readFileSync(t.resolve(e,`..`,`package.json`),`utf8`));return n}function ae(t,n){let r=e(import.meta.url),i=(()=>{try{let e=r.resolve(`@cfp-studio/type-analyzer/package.json`);return JSON.parse(f.readFileSync(e,`utf8`)).version??`unknown`}catch{return`unknown`}})();return`${t.split(`/`).pop()||`unknown`}@${n}+ta@${i}`}function E(e){try{return t.resolve(e,`node_modules`,`.cfp`,`v${ie()}`)}catch(e){throw Error(`无法获取 @cfp-studio/core 的版本号.\n${e}`)}}function D(e,n,r){return t.join(E(e),`scan-${ae(n,r)}`)}function oe(e){let n=t.resolve(e,`node_modules`,`.previewjs`);try{return f.existsSync(n)?(f.rmSync(n,{recursive:!0,force:!0}),!0):!1}catch{return!1}}function se(e,n,r,i){let a=D(e,n,r),o=t.join(a,`components.json`),s={cacheDir:a,exists:!1,detectionStartTimestamp:null,cachedComponents:0,cachedStories:0,skippedSourceFiles:0,sourceFiles:i.length},c=null;try{if(!f.existsSync(o))return s;c=JSON.parse(f.readFileSync(o,`utf8`))}catch{return{...s,exists:!0}}let l=typeof c?.detectionStartTimestamp==`number`?c.detectionStartTimestamp:0,u=0;for(let e of i)try{f.statSync(e).mtimeMs<l&&(u+=1)}catch{}return{cacheDir:a,exists:!0,detectionStartTimestamp:l||null,cachedComponents:Array.isArray(c?.components)?c.components.length:0,cachedStories:Array.isArray(c?.stories)?c.stories.length:0,skippedSourceFiles:u,sourceFiles:i.length}}function ce(e,t,n){let r=D(e,t,n);try{return f.existsSync(r)?(f.rmSync(r,{recursive:!0,force:!0}),!0):!1}catch{return!1}}async function O(e,t,n={}){return k(e,t,{...n,gitignore:!0})}async function k(e,n,r){let i=await A(e),a=t.relative(i,e),o=a?a.split(t.sep).join(`/`)+`/`:``,s=(r.ignoredPaths??[]).map(e=>o+e),c=await _(o+n,{gitignore:r.gitignore,ignore:[`**/node_modules/**`,...s],cwd:i,absolute:!0,followSymbolicLinks:!1,suppressErrors:!0,deep:r.maxDepth}),l=e.replace(/\\/g,`/`);return l.endsWith(`/`)||(l+=`/`),c.filter(e=>e.startsWith(l)).sort()}async function le(e,t=`**/*.@(js|jsx|ts|tsx|svelte|vue)`,n=[]){let[r,i]=await Promise.all([k(e,t,{ignoredPaths:n,gitignore:!0}),k(e,t,{ignoredPaths:n,gitignore:!1})]),a=new Set(r);return i.filter(e=>!a.has(e))}async function A(e,n=e){try{if(await u.exists(t.join(e,`.git`)))return e;let r=t.dirname(e);return!r||r===e?n:A(r,n)}catch{return n}}const j=new Set([`jsconfig.json`,`tsconfig.json`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`.gitignore`]),ue=g();function M(e,n,i,a={}){return ue(async()=>{e.debug(`开始扫描组件,扫描参数: ${JSON.stringify(a)}`);let o=Date.now(),s=t.join(D(n.rootDir,n.frameworkPluginName,n.frameworkPluginVersion??`unknown`),`components.json`),c=await(async()=>{if(a.filePaths)return a.filePaths.map(e=>t.join(n.rootDir,e));e.debug(`扫描目录: ${n.rootDir},采集可扫描文件`);let r=await O(n.rootDir,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,{ignoredPaths:i.ignoredPaths});return e.debug(`找到 ${r.length} 个包含组件的文件`),r})(),l=new Set(c.map(e=>t.relative(n.rootDir,e).replace(/\\/g,`/`))),d={detectionStartTimestamp:0,components:[],stories:[]};if(u.existsSync(s))try{d=JSON.parse(u.readFileSync(s,`utf8`))}catch{e.warn(`无法转换 ${s} 中存储的缓存信息`)}d.detectionStartTimestamp<await fe(n.rootDir)&&(d={detectionStartTimestamp:0,components:[],stories:[]});let f=c.filter(e=>{let t=n.reader.readSync(e);return t?.kind===`file`&&(a.forceRefresh||t.lastModifiedMillis()>=d.detectionStartTimestamp)}),p=new Set(f.map(e=>t.relative(n.rootDir,e).replace(/\\/g,`/`))),m=({id:e})=>{let t=r(e).filePath;return l.has(t)&&!p.has(t)},h=d.components.filter(m),g=d.stories.filter(m),{components:_,stories:v}=await de(e,n,i,f),y=[...h,..._],b=[...g,...v];if(!a.filePaths){await u.mkdirp(t.dirname(s));let e={detectionStartTimestamp:o,components:y,stories:b};await u.writeFile(s,JSON.stringify(e))}return{components:y,stories:b}})}async function de(e,n,r,i){let a=[],o=[];if(i.length===0)return{components:a,stories:o};e.debug(`在下述文件中查找组件:\n- ${i.map(e=>t.relative(n.rootDir,e)).join(`
|
|
2
|
+
- `)}`);let s=await r.crawlFiles(i);e.debug(`组件检测完成`);for(let e of s.components)a.push({id:e.id,sourcePosition:e.sourcePosition,exported:e.exported});for(let e of s.stories)o.push({id:e.id,sourcePosition:e.sourcePosition,associatedComponentId:e.associatedComponent?.id||null});return{components:a,stories:o}}async function fe(e){let n=t.join(e,`node_modules`),r=0;if(await u.pathExists(n))for(let e of await u.readdir(n)){let i=t.join(n,e),a=await u.lstat(i);(a.isDirectory()||a.isSymbolicLink())&&(r=Math.max(r,a.mtimeMs))}for(let n of j){let i=t.join(e,n);if(await u.pathExists(i)){let e=await u.stat(i);r=Math.max(r,e.mtimeMs)}}return r}async function pe(e){for(let t=e;;t++)if(await me(t))return t}async function me(e){return new Promise(t=>{let n=v.createServer();n.unref(),n.on(`error`,()=>t(!1)),n.listen(e,()=>{n.close(()=>{t(!0)})})})}const he=e(import.meta.url);async function N(e,n){let r=t.join(n,`package.json`);if(!await u.pathExists(r))return{};let{dependencies:i,devDependencies:a,peerDependencies:o}=JSON.parse(await u.readFile(r,`utf8`)),s={...i,...a,...o},c=new Map;for(let[r,i]of Object.entries(s)){let a=0;typeof i==`string`&&(a=i.startsWith(`^`)||i.startsWith(`~`)?Number.parseInt(i.slice(1)):Number.parseInt(i)),c.set(r,{majorVersion:a,readInstalledVersion:async()=>{try{let e=ge(r,n),i=e;for(;i!==t.dirname(i);){let e=t.join(i,`package.json`);if(u.existsSync(e)){let t=JSON.parse(await u.readFile(e,`utf8`));if(typeof t.version==`string`)return t.version;throw Error(`包: ${e} 的版本号异常`)}i=t.dirname(i)}throw Error(`根据模块: ${e} 的入口路径无法找到 package.json`)}catch(t){return e.error(t,`无法读取包: ${r} 的安装版本, 你可能没有正确安装项目的依赖,请重新安装。`),null}}})}return Object.fromEntries(c)}function ge(e,t){try{return he.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 P=[`preview.config.js`,`preview.config.mjs`,`preview.config.ts`,`preview.config.cjs`,`preview.config.mts`,`preview.config.cts`];async function _e(e,n){let r={};for(let i of P){let a=t.join(e,i);if(f.existsSync(a))try{let t=await ee({command:`serve`,mode:`development`},i,e,n);if(t){r=t.config;break}}catch(e){throw e instanceof Error&&typeof e.message==`string`&&e.message.includes(`config 必须导出或者返回一个对象`)?Error(`请使用一个 preview.config.js 的默认导出`):e}}return r}function F(e){let t=e;return t.startsWith(`Error: Build failed with 1 error:
|
|
3
3
|
`)&&(t=t.substring(e.indexOf(`
|
|
4
4
|
`)+1)),t.startsWith(`Error:`)&&(t=t.substring(t.indexOf(`:`)+1)),t=t.trim(),`<html>
|
|
5
5
|
<head>
|
|
@@ -32,7 +32,7 @@ import{createRequire as e}from"node:module";import t from"node:path";import{deco
|
|
|
32
32
|
<\/script>
|
|
33
33
|
</head>
|
|
34
34
|
<body>${re(e)}</body>
|
|
35
|
-
</html>`}const
|
|
35
|
+
</html>`}const ve=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]),ye=/import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;function be(){return{name:`previewjs:css-modules-without-suffix`,async transform(e,n){let r=n.split(`?`)[0];return!r||!ve.has(t.extname(r))?null:e.replace(ye,`import $1 from "$3.$4?$5&.module.css"`)}}}const I=`__fakeValueExport__`;let L=null;function xe(){return L??=import(`typescript`).then(e=>e.default??e),L}function Se(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 Ce(r,i)},t.set(r,a)),a.names.length!==0)return`${n}\nconst ${I} = null;\nexport { ${a.names.map(e=>`${I} as ${e}`).join(`, `)} };`}}}async function Ce(e,t){let n=await xe(),r=e.endsWith(`.tsx`);return we(n,n.createSourceFile(e,t,n.ScriptTarget.Latest,!1,r?n.ScriptKind.TSX:n.ScriptKind.TS))}function we(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=Te(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 Te(e,t){let n=t.modifiers;return n!==void 0&&n.some(t=>t.kind===e.SyntaxKind.ExportKeyword)}function Ee(){return{name:`previewjs:invalidate-stories-modules-on-update`,enforce:`post`,transform:e=>e.includes(`import.meta.hot.accept(`)?`${e}
|
|
36
36
|
if (import.meta?.hot) {
|
|
37
37
|
import.meta.hot.accept(newModule => {
|
|
38
38
|
if (newModule?.default?.component) {
|
|
@@ -40,11 +40,11 @@ import{createRequire as e}from"node:module";import t from"node:path";import{deco
|
|
|
40
40
|
}
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
|
-
`:null}}function
|
|
43
|
+
`:null}}function De(){return{name:`previewjs:local-eval`,enforce:`post`,transform:(e,t)=>t.indexOf(`/node_modules/`)!==-1||t.indexOf(`?`)!==-1?null:`${e}
|
|
44
44
|
export const PreviewJsEval = (code, args = {}) => {
|
|
45
45
|
return eval("(({ " + Object.keys(args).join(", ") + "}) => { " + code + " })(args)");
|
|
46
46
|
}
|
|
47
|
-
`}}function
|
|
47
|
+
`}}function Oe(){return{name:`previewjs:preview-script`,load(e){if(!e.startsWith(`/__previewjs_internal__/preview.js?p=`))return null;let t=e.substring(37);return ke(JSON.parse(Buffer.from(t,`base64url`).toString(`utf8`)))}}}function ke({previewablePath:e,previewableName:t,wrapperPath:n,wrapperName:r,detectedGlobalCssFilePaths:i}){return`
|
|
48
48
|
// 导入初始化监听器和预览的函数
|
|
49
49
|
import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";
|
|
50
50
|
// 初始化监听器
|
|
@@ -123,4 +123,4 @@ import{createRequire as e}from"node:module";import t from"node:path";import{deco
|
|
|
123
123
|
function loadFreshWrapperModule() {
|
|
124
124
|
return import(/* @vite-ignore */ "/${n}?t=" + Date.now());
|
|
125
125
|
}
|
|
126
|
-
`}function De({rootDir:e,publicDir:n}){return{name:`previewjs:public-asset-import`,resolveId:async(r,i)=>{if(!i||!r.startsWith(`/`)||r.startsWith(`/__previewjs__/`))return null;let a=t.join(e,n),o=t.join(a,r);return!o.startsWith(a+t.sep)||!await l.pathExists(o)?null:r}}}function R(e){let t=e;return t.match(/^[a-z]:/)&&(t=t[0]?.toUpperCase()+e.substring(1)),t.replace(/\\/g,`/`)}const z=`/@cfp-studio-virtual:`,B=`/@id/__x00__`,V=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]);function H(e){let t=e;return t.startsWith(z)&&(t=t.slice(21)),t.startsWith(`\0`)&&(t=t.slice(1)),t.startsWith(B)&&(t=t.slice(12)),[t,t!==e]}function Oe(e){let{reader:n,rootDir:r}=e;return{name:`previewjs:virtual-fs`,resolveId:async(e,n)=>{let[r,a]=n?H(n):[null,!1];if(e.indexOf(`/node_modules/`)!==-1)return null;let[o]=H(e);o=o.split(`?`,2)[0]??``;let s=t.extname(o),c;if(t.isAbsolute(o))c=o;else{if(!r)return null;if(s&&!V.has(s)&&s!==`.svg`)return t.join(t.dirname(r),o);c=t.join(t.dirname(r),o)}let u=await i(c);if(u){let[e]=u;return await l.pathExists(e)&&!a?null:(c.endsWith(s)||(c+=s),z+e.replace(/\\/g,`/`))}return null},load:async n=>{let a=n;if(a.indexOf(`/node_modules/`)!==-1)return null;a.startsWith(z)&&(a=a.slice(21)),a.startsWith(`\0`)&&(a=a.slice(1)),a.startsWith(B)&&(a=a.slice(12));let o=await i(a);if(!o)return null;let[s,c]=o,l=!1;for(let n of e.allowedAbsolutePaths){let e=t.relative(n,s);if(e&&!e.startsWith(`..`)&&!t.isAbsolute(e)){l=!0;break}}if(!l)return e.logger.error(`试图访问的 ${s} 文件在运行访问的目录之外. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(c.kind!==`file`)return e.logger.error(`无法读取文件:${s}`),null;let u=await c.read(),d=t.extname(s);if(!V.has(d))return u;let f=t.extname(n);return{code:!n.includes(`__previewjs_internal__`)&&(f===``||f===`.js`)?(await ne(u,s,{loader:s.endsWith(`.ts`)?`ts`:`tsx`,format:`esm`,target:`es2020`,sourcefile:t.relative(r,s),...e.esbuildOptions})).code:u}},transform:(e,t)=>t.startsWith(z)?{code:e,map:{mappings:``,names:[],sources:[],version:3}}:null,handleHotUpdate:async i=>{let a=e.moduleGraph();if(!a)return null;let o=t.relative(r,i.file),s=t.join(r,o),c=await n.read(s);if(!c||c.kind!==`file`)return null;let l=z+R(s),u=a.getModuleById(l);return u&&[u]}};async function i(e){return await a(e)||await a(t.join(r,e))}async function a(e){for(let r of[``,...V,...[...V].map(e=>`${t.sep}index${e}`)]){let t=`${e}${r}`,i=await n.read(t);if(i?.kind===`file`)return[t,i]}return null}}function ke(e,t){let n=e.environments?Object.values(e.environments):[];if(n.length>0)for(let e of n)e.moduleGraph.onFileChange(t);else e.moduleGraph.onFileChange(t);for(let n of e.watcher.listeners(`change`))try{n(t)}catch{}}function Ae(e={platform:process.platform},t){return t&&typeof t.usePolling==`boolean`||e.platform!==`win32`?t:{...t,usePolling:!0,interval:t?.interval??300}}const U=e(import.meta.url);function W(e){let n=G(e);if(!n)return e;let r=t.join(t.dirname(t.dirname(n)),`src`,`index.ts`);return l.existsSync(r)?r:n}function je(e){let n=G(e);return n?t.dirname(t.dirname(n)):void 0}function Me(e){for(let n of K()){let r=n.endsWith(`.mjs`)||n.endsWith(`.js`)?t.dirname(n):n,i=t.join(r,`node_modules`,...e.split(`/`));if(l.existsSync(i))return i}}function G(e){for(let n of K()){let r=_(n.endsWith(t.sep)?n:`${n}${t.sep}`).href;try{return g(import.meta.resolve(e,r))}catch{}try{return U.resolve(e,{paths:[n]})}catch{}}}function K(){let e=[Pe];try{e.push(t.dirname(U.resolve(`@cfp-studio/iframe/package.json`)))}catch{}return e}const q=[`@cfp-studio/fiber-reader`,`@cfp-studio/analyzer-api`];function Ne(){let e=[];for(let t of q){let n=je(t)??Me(t);n&&e.push(n)}return[...new Set(e)]}const Pe=t.dirname(g(import.meta.url)),Fe=[`.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`],J=[`index`,`global`,`globals`,`style`,`styles`,`app`],Y=[`css`,`sass`,`scss`,`less`,`styl`,`stylus`],Ie=J.flatMap(e=>Y.map(t=>`${e}.${t}`)),Le=new Set([...P,...j,...Fe,...Ie,`vite.config.js`,`vite.config.ts`,`svelte.config.js`]);async function X(e){return e?.kind===`starting`?e.promise:e}var Re=class{#e=null;#t;#n={onChange:(e,n)=>{this.onFileChanged(t.resolve(e),n).catch(e=>this.options.logger.error(e))}};get state(){return this.#e}constructor(e){this.options=e;let t=c.Router();t.use(async(e,t,n)=>{let r=await X(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,r){return this.#t(async()=>{try{let i=await X(this.#e);if(!i)return F(`Vite server is not running`);if(i.kind===`error`)return F(i.error);let a=await l.readFile(this.options.shadowHtmlFilePath,`utf-8`),{config:o,viteServer:s}=i,{filePath:c,name:u}=n(r),d=c.replace(/\\/g,`/`),f=o.wrapper,p=f&&await l.pathExists(t.join(this.options.rootDir,f.path))?f.path.replace(/\\/g,`/`):null;return await s.transformIndexHtml(e,a.replace(`<!-- %OPTIONAL_HEAD_CONTENT% -->`,`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(JSON.stringify({previewablePath:d,previewableName:u,wrapperPath:p,wrapperName:f?.componentName||null,detectedGlobalCssFilePaths:o.detectedGlobalCssFilePaths}),`utf8`).toString(`base64url`)}"><\/script>`))}catch(e){return F(`${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 n=await me(this.options.rootDir,$(this.options.logger)),r=await O(this.options.rootDir,`**/@(${J.join(`|`)}).@(${Y.join(`|`)})`,{maxDepth:3}),i={...n,wrapper:n.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:r.map(e=>t.relative(this.options.rootDir,e))},a=[],o=null;for(let e of[`tsconfig.json`,`jsconfig.json`]){let n=t.join(this.options.rootDir,e);try{if(await l.pathExists(n)){let e=C(n)||null;if(e){o=Ve.parse(e);break}}}catch(e){this.options.logger.warn(`Unable to load tsconfig from ${n}: ${e}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(o||null,null,2)}`);let s=o?.compilerOptions?.baseUrl||``,c=o?.compilerOptions?.paths||{},u=s.startsWith(`./`)?s.substring(1):s;u&&!u.endsWith(`/`)&&(u+=`/`);for(let[e,n]of Object.entries(c)){let r=n[0];if(!r)continue;let i=e.endsWith(`/*`)?e.slice(0,e.length-2):e,o=r.endsWith(`/*`)?r.slice(0,r.length-2):r;a.push({find:i,replacement:t.join(this.options.rootDir,s,o)})}let d=await w.loadConfigFromFile({command:`serve`,mode:`development`},void 0,this.options.rootDir),f=w.createLogger($(this.options.logger)),p=this.options.frameworkPlugin.viteConfig(await Q([...d?.config.plugins||[],...i.vite?.plugins||[]])),m=i.vite?.publicDir||d?.config.publicDir||p.publicDir||i.publicDir||`public`,h=Be(this.options.reader,await Q([S({root:this.options.rootDir}),Te(),Oe({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:[...i.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[te(this.options.rootDir)],...Ne()],moduleGraph:()=>this.#e?.kind===`running`?this.#e.viteServer.moduleGraph:null,esbuildOptions:p.esbuild||{}}),we(),Ce(),ye({readFile:e=>this.options.reader.read(e).then(e=>e?.kind===`file`?e.read():null)}),_e(),De({rootDir:this.options.rootDir,publicDir:m}),p.plugins]));this.options.logger.debug(`Creating Vite server`);let g=await w.createServer({...p,...d?.config,...i.vite,optimizeDeps:He(p.optimizeDeps,d?.config.optimizeDeps,i.vite?.optimizeDeps),configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,watch:Ae(void 0,i.vite?.server?.watch),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:(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:i.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,...i.vite?.define},resolve:{...d?.config.resolve,...i.vite?.resolve,alias:[{find:`@cfp-studio/fiber-reader`,replacement:W(`@cfp-studio/fiber-reader`)},...q.filter(e=>e!==`@cfp-studio/fiber-reader`).map(e=>({find:e,replacement:W(e)})),...Z(i.vite?.resolve?.alias),...Z(i.alias),...Z(d?.config.resolve?.alias),...a,...Z(p.resolve?.alias),...ze(u)?[{find:/^~(.*)/,replacement:`${u}$1`},{find:`@`,replacement:u}]:[]]}});e({kind:`running`,config:i,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 X(this.#e);return t?.kind===`running`&&await t.viteServer.close(),e?this.start():this.#e=null})}async onFileChanged(e,n){let r=await X(this.state);if(!r)return;if(!n.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(t.relative(this.options.rootDir,e)),Le.has(t.basename(e)))){this.options.logger.info(`检测到依赖变化. 重启服务...`),await this.stop({restart:!0});return}if(r.kind!==`running`)return;let{viteServer:i,config:a}=r;n.virtual?ke(i,R(e)):a.wrapper&&e===t.resolve(this.options.rootDir,a.wrapper.path)&&(i.moduleGraph.invalidateAll(),i.ws.send({type:`full-reload`}))}};function Z(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({find:e,replacement:t})):[]}function ze(e){return e!==``&&e!==`./`&&e!==`.`}async function Q(e){let t=[];for(let n of await Promise.all(e))n&&(Array.isArray(n)?t.push(...await Q(n)):t.push(n));return t}function $(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 Be(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 Ve=T.object({compilerOptions:T.object({baseUrl:T.string().optional(),paths:T.record(T.array(T.string())).optional()}).optional()});function He(...e){let t=e.filter(e=>!!e);if(t.length===0)return;let n={};for(let e of t)Object.assign(n,e);let r=t.flatMap(e=>e.exclude??[]);r.length>0&&(n.exclude=[...new Set(r)]);let i=t.flatMap(e=>e.include??[]);i.length>0&&(n.include=[...new Set(i)]);let a=t.map(e=>e.esbuildOptions).filter(Boolean);if(a.length>0){let e={};for(let t of a)Object.assign(e,t);let t=a.flatMap(e=>e?.plugins??[]);t.length>0&&(e.plugins=t),n.esbuildOptions=e}return n}var Ue=class{constructor(e){this.options=e,this.viteManager=null,this.status={kind:`stopped`},this.disposeObserver=null,this.transformingReader=o([e.reader,a({mapping:{from:e.frameworkPlugin.previewDirPath,to:t.join(e.rootDir,`__previewjs_internal__`,`renderer`)},watch:!1}),a({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 b(e)}}async startFromStopped(){this.status={kind:`starting`,promise:(async()=>{let e=c.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:n,disposeHttpServer:r}=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 Re({rootDir:this.options.rootDir,shadowHtmlFilePath:t.join(this.options.previewDirPath,`index.html`),reader:this.transformingReader,cacheDir:t.join(D(this.options.rootDir),`vite`),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:n,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug(`预览服务已就绪`),this.status={kind:`started`,onStop:r}})()},await this.status.promise;for(let e=0;;e++)try{await x.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}},We=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}`}}}};async function Ge(e,t,n){let r=await N(e,t);for(let e of n)if(e.info&&await e.isCompatible(r,t))return e.info?.name;return null}const{pino:Ke}=d,qe=f,Je=e(import.meta.url);process.on(`uncaughtException`,e=>{console.error(`Core 遇到未捕获的异常`,e)}),process.on(`unhandledRejection`,e=>{console.error(`Core 遇到未处理的 Promise 对象`,e)});async function Ye({rootDir:e,frameworkPlugin:o,logger:l=Ke({level:process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase()||`warn`},qe({colorize:!0})),reader:d=a(),onServerStart:f=()=>Promise.resolve({})}){if(!o.info)throw Error(`framework plugin 与当前版本 ${E()} 不兼容. 请升级.`);if(o.info.apiVersion>5)throw Error(` ${o.info.name} 的 API 版本是 ${o.info.apiVersion}. 高于当前安装的 ${E()}, 请升级至最新版本.`);let p=await N(l,e);if(!await o.isCompatible(p,e))throw Error(` ${o.info.name} 与当前工作区的前端框架版本不兼容。`);l.info(`使用 ${o.info.name} 在目录: ${e} 中创建工作区`);let m=await o.create({rootDir:e,reader:d,logger:l,dependencies:p}),h=new Set,g={frameworkPluginName:o.info.name,crawlFiles:m.crawlFiles,crawlProject:e=>M(l,g,m,e??{}),findGitignoredSourceFiles:()=>oe(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,m.ignoredPaths),typeAnalyzer:m.typeAnalyzer,rootDir:e,reader:d,startServer:async({asMiddleware:a,port:p,clientPort:_,onStop:v}={})=>{let y=p||await ue(3140),b=new We(l);b.registerRPC(r.Analyze,async({previewableIds:r})=>{l.debug(`分析: ${r.join(`, `)}`);let a=await m.crawlFiles([...new Set(r.map(r=>t.join(e,n(r).filePath)))]);l.debug(`检测到 ${a.components.length} 个组件和 ${a.stories.length} 个story`);let o=[],s=Object.fromEntries(a.components.map(e=>[e.id,e])),c=Object.fromEntries(a.stories.map(e=>[e.id,e])),u={};for(let e of r){let t=s[e],r=c[e],a;if(t){let n;l.debug(`分析组件: ${e}`),{props:n,types:a}=await t.analyze(),o.push({kind:`component`,id:e,exported:t.exported,sourcePosition:t.sourcePosition,props:n})}else if(r){let t;r.associatedComponent?({props:t,types:a}=await r.associatedComponent.analyze(),l.debug(`分析 story: ${e} 的关联组件`)):(l.debug(`story: ${e} 没有关联的组件`),t=i,a={});let n=null;({args:n}=await r.analyze()),o.push({kind:`story`,id:e,sourcePosition:r.sourcePosition,associatedComponentId:r.associatedComponent?.id||null,props:t,args:n}),l.debug(`story args: ${JSON.stringify(n)}`)}else{let{filePath:t,name:r}=n(e);throw Error(`在 ${t} 中未找到组件 ${r}. `)}u={...u,...a}}return{previewables:o,types:u}}),b.registerRPC(r.GetInfo,async()=>({frameworkPlugin:o.info})),b.registerRPC(r.CrawlFiles,e=>M(l,g,m,e));let x=[s(),c.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=a?async e=>{let t=a.register(e);return{server:a.server,disposeHttpServer:async()=>{t()}}}:async e=>{l.debug(`启动 Express 服务器`);let t=c();t.use(e);let n=await new Promise(e=>{let n=t.listen(y,()=>{l.info(`${E()} 预览服务运行在 http://localhost:${y}.`),e(n)})}),r=u({server:n,gracefulTerminationTimeout:0});return{server:n,disposeHttpServer:async()=>{await r.terminate(),l.info(`${E()} 预览服务器已停止.`)}}},C=new Ue({reader:d,rootDir:e,previewDirPath:t.join(t.dirname(t.dirname(Je.resolve(`@cfp-studio/iframe`))),`preview`),frameworkPlugin:m,logger:l,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 Xe(e){let n=t.resolve(e);for(;n!==t.dirname(n);){if(l.existsSync(t.join(n,`package.json`)))return n;n=t.dirname(n)}return null}export{Ye as createWorkspace,Ge as findCompatiblePlugin,Xe as findWorkspaceRoot,R as toVitePath};
|
|
126
|
+
`}function Ae({rootDir:e,publicDir:n}){return{name:`previewjs:public-asset-import`,resolveId:async(r,i)=>{if(!i||!r.startsWith(`/`)||r.startsWith(`/__previewjs__/`))return null;let a=t.join(e,n),o=t.join(a,r);return!o.startsWith(a+t.sep)||!await u.pathExists(o)?null:r}}}function R(e){let t=e;return t.match(/^[a-z]:/)&&(t=t[0]?.toUpperCase()+e.substring(1)),t.replace(/\\/g,`/`)}const z=`/@cfp-studio-virtual:`,B=`/@id/__x00__`,V=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]);function H(e){let t=e;return t.startsWith(z)&&(t=t.slice(21)),t.startsWith(`\0`)&&(t=t.slice(1)),t.startsWith(B)&&(t=t.slice(12)),[t,t!==e]}function je(e){let{reader:n,rootDir:r}=e;return{name:`previewjs:virtual-fs`,resolveId:async(e,n)=>{let[r,a]=n?H(n):[null,!1];if(e.indexOf(`/node_modules/`)!==-1)return null;let[o]=H(e);o=o.split(`?`,2)[0]??``;let s=t.extname(o),c;if(t.isAbsolute(o))c=o;else{if(!r)return null;if(s&&!V.has(s)&&s!==`.svg`)return t.join(t.dirname(r),o);c=t.join(t.dirname(r),o)}let l=await i(c);if(l){let[e]=l;return await u.pathExists(e)&&!a?null:(c.endsWith(s)||(c+=s),z+e.replace(/\\/g,`/`))}return null},load:async n=>{let a=n;if(a.indexOf(`/node_modules/`)!==-1)return null;a.startsWith(z)&&(a=a.slice(21)),a.startsWith(`\0`)&&(a=a.slice(1)),a.startsWith(B)&&(a=a.slice(12));let o=await i(a);if(!o)return null;let[s,c]=o,l=!1;for(let n of e.allowedAbsolutePaths){let e=t.relative(n,s);if(e&&!e.startsWith(`..`)&&!t.isAbsolute(e)){l=!0;break}}if(!l)return e.logger.error(`试图访问的 ${s} 文件在运行访问的目录之外. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(c.kind!==`file`)return e.logger.error(`无法读取文件:${s}`),null;let u=await c.read(),d=t.extname(s);if(!V.has(d))return u;let f=t.extname(n);return{code:!n.includes(`__previewjs_internal__`)&&(f===``||f===`.js`)?(await ne(u,s,{loader:s.endsWith(`.ts`)?`ts`:`tsx`,format:`esm`,target:`es2020`,sourcefile:t.relative(r,s),...e.esbuildOptions})).code:u}},transform:(e,t)=>t.startsWith(z)?{code:e,map:{mappings:``,names:[],sources:[],version:3}}:null,handleHotUpdate:async i=>{let a=e.moduleGraph();if(!a)return null;let o=t.relative(r,i.file),s=t.join(r,o),c=await n.read(s);if(!c||c.kind!==`file`)return null;let l=z+R(s),u=a.getModuleById(l);return u&&[u]}};async function i(e){return await a(e)||await a(t.join(r,e))}async function a(e){for(let r of[``,...V,...[...V].map(e=>`${t.sep}index${e}`)]){let t=`${e}${r}`,i=await n.read(t);if(i?.kind===`file`)return[t,i]}return null}}function Me(e,t){let n=e.environments?Object.values(e.environments):[];if(n.length>0)for(let e of n)e.moduleGraph.onFileChange(t);else e.moduleGraph.onFileChange(t);for(let n of e.watcher.listeners(`change`))try{n(t)}catch{}}function Ne(e={platform:process.platform},t){return t&&typeof t.usePolling==`boolean`||e.platform!==`win32`?t:{...t,usePolling:!0,interval:t?.interval??300}}const U=e(import.meta.url);function W(e){let n=G(e);if(!n)return e;let r=Pe(e),i=t.dirname(t.dirname(n)),a=r?t.join(i,`src`,`${r}.ts`):t.join(i,`src`,`index.ts`);return u.existsSync(a)?a:n}function Pe(e){let t=e.split(`/`),n=e.startsWith(`@`)?2:1;return t.length===n+1?t[n]:void 0}function Fe(e){let n=G(e);return n?t.dirname(t.dirname(n)):void 0}function Ie(e){for(let n of K()){let r=n.endsWith(`.mjs`)||n.endsWith(`.js`)?t.dirname(n):n,i=t.join(r,`node_modules`,...e.split(`/`));if(u.existsSync(i))return i}}function G(e){for(let n of K()){let r=h(n.endsWith(t.sep)?n:`${n}${t.sep}`).href;try{return m(import.meta.resolve(e,r))}catch{}try{return U.resolve(e,{paths:[n]})}catch{}}}function K(){let e=[Re];try{e.push(t.dirname(U.resolve(`@cfp-studio/iframe/package.json`)))}catch{}return e}const q=[`@cfp-studio/fiber-reader`,`@cfp-studio/analyzer-api/error-panel`];function Le(){let e=[];for(let t of q){let n=Fe(t)??Ie(t);n&&e.push(n)}return[...new Set(e)]}const Re=t.dirname(m(import.meta.url)),ze=[`.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`],J=[`index`,`global`,`globals`,`style`,`styles`,`app`],Y=[`css`,`sass`,`scss`,`less`,`styl`,`stylus`],Be=J.flatMap(e=>Y.map(t=>`${e}.${t}`)),Ve=new Set([...P,...j,...ze,...Be,`vite.config.js`,`vite.config.ts`,`svelte.config.js`]);async function X(e){return e?.kind===`starting`?e.promise:e}var He=class{#e=null;#t;#n={onChange:(e,n)=>{this.onFileChanged(t.resolve(e),n).catch(e=>this.options.logger.error(e))}};get state(){return this.#e}constructor(e){this.options=e;let t=l.Router();t.use(async(e,t,n)=>{let r=await X(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=g()}async loadIndexHtml(e,n){return this.#t(async()=>{try{let i=await X(this.#e);if(!i)return F(`Vite server is not running`);if(i.kind===`error`)return F(i.error);let a=await u.readFile(this.options.shadowHtmlFilePath,`utf-8`),{config:o,viteServer:s}=i,{filePath:c,name:l}=r(n),d=c.replace(/\\/g,`/`),f=o.wrapper,p=f&&await u.pathExists(t.join(this.options.rootDir,f.path))?f.path.replace(/\\/g,`/`):null;return await s.transformIndexHtml(e,a.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:o.detectedGlobalCssFilePaths}),`utf8`).toString(`base64url`)}"><\/script>`))}catch(e){return F(`${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 n=await _e(this.options.rootDir,$(this.options.logger)),r=await O(this.options.rootDir,`**/@(${J.join(`|`)}).@(${Y.join(`|`)})`,{maxDepth:3}),i={...n,wrapper:n.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:r.map(e=>t.relative(this.options.rootDir,e))},a=[],o=null;for(let e of[`tsconfig.json`,`jsconfig.json`]){let n=t.join(this.options.rootDir,e);try{if(await u.pathExists(n)){let e=S(n)||null;if(e){o=Ge.parse(e);break}}}catch(e){this.options.logger.warn(`Unable to load tsconfig from ${n}: ${e}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(o||null,null,2)}`);let s=o?.compilerOptions?.baseUrl||``,c=o?.compilerOptions?.paths||{},l=s.startsWith(`./`)?s.substring(1):s;l&&!l.endsWith(`/`)&&(l+=`/`);for(let[e,n]of Object.entries(c)){let r=n[0];if(!r)continue;let i=e.endsWith(`/*`)?e.slice(0,e.length-2):e,o=r.endsWith(`/*`)?r.slice(0,r.length-2):r;a.push({find:i,replacement:t.join(this.options.rootDir,s,o)})}let d=await C.loadConfigFromFile({command:`serve`,mode:`development`},void 0,this.options.rootDir),f=C.createLogger($(this.options.logger)),p=this.options.frameworkPlugin.viteConfig(await Q([...d?.config.plugins||[],...i.vite?.plugins||[]])),m=i.vite?.publicDir||d?.config.publicDir||p.publicDir||i.publicDir||`public`,h=We(this.options.reader,await Q([x({root:this.options.rootDir}),Oe(),je({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:[...i.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[te(this.options.rootDir)],...Le()],moduleGraph:()=>this.#e?.kind===`running`?this.#e.viteServer.moduleGraph:null,esbuildOptions:p.esbuild||{}}),De(),Ee(),Se({readFile:e=>this.options.reader.read(e).then(e=>e?.kind===`file`?e.read():null)}),be(),Ae({rootDir:this.options.rootDir,publicDir:m}),p.plugins]));this.options.logger.debug(`Creating Vite server`);let g=await C.createServer({...p,...d?.config,...i.vite,optimizeDeps:Ke(p.optimizeDeps,d?.config.optimizeDeps,i.vite?.optimizeDeps),configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,watch:Ne(void 0,i.vite?.server?.watch),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:(e,t)=>f.info(`[vite] ${e}`,t),warn:(e,t)=>f.warn(`[vite] ${e}`,t),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(`[vite] ${e}`,t)},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:h,define:{__filename:void 0,__dirname:void 0,process:void 0,...p.define,...d?.config.define,...i.vite?.define},resolve:{...d?.config.resolve,...i.vite?.resolve,alias:[{find:`@cfp-studio/fiber-reader`,replacement:W(`@cfp-studio/fiber-reader`)},...q.filter(e=>e!==`@cfp-studio/fiber-reader`).map(e=>({find:RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`),replacement:W(e)})),...Z(i.vite?.resolve?.alias),...Z(i.alias),...Z(d?.config.resolve?.alias),...a,...Z(p.resolve?.alias),...Ue(l)?[{find:/^~(.*)/,replacement:`${l}$1`},{find:`@`,replacement:l}]:[]]}});e({kind:`running`,config:i,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 X(this.#e);return t?.kind===`running`&&await t.viteServer.close(),e?this.start():this.#e=null})}async onFileChanged(e,n){let r=await X(this.state);if(!r)return;if(!n.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(t.relative(this.options.rootDir,e)),Ve.has(t.basename(e)))){this.options.logger.info(`检测到依赖变化. 重启服务...`),await this.stop({restart:!0});return}if(r.kind!==`running`)return;let{viteServer:i,config:a}=r;n.virtual?Me(i,R(e)):a.wrapper&&e===t.resolve(this.options.rootDir,a.wrapper.path)&&(i.moduleGraph.invalidateAll(),i.ws.send({type:`full-reload`}))}};function Z(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({find:e,replacement:t})):[]}function Ue(e){return e!==``&&e!==`./`&&e!==`.`}async function Q(e){let t=[];for(let n of await Promise.all(e))n&&(Array.isArray(n)?t.push(...await Q(n)):t.push(n));return t}function $(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 We(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 Ge=w.object({compilerOptions:w.object({baseUrl:w.string().optional(),paths:w.record(w.array(w.string())).optional()}).optional()});function Ke(...e){let t=e.filter(e=>!!e);if(t.length===0)return;let n={};for(let e of t)Object.assign(n,e);let r=t.flatMap(e=>e.exclude??[]);r.length>0&&(n.exclude=[...new Set(r)]);let i=t.flatMap(e=>e.include??[]);i.length>0&&(n.include=[...new Set(i)]);let a=t.map(e=>e.esbuildOptions).filter(Boolean);if(a.length>0){let e={};for(let t of a)Object.assign(e,t);let t=a.flatMap(e=>e?.plugins??[]);t.length>0&&(e.plugins=t),n.esbuildOptions=e}return n}var qe=class{constructor(e){this.options=e,this.viteManager=null,this.status={kind:`stopped`},this.disposeObserver=null,this.transformingReader=s([e.reader,o({mapping:{from:e.frameworkPlugin.previewDirPath,to:t.join(e.rootDir,`__previewjs_internal__`,`renderer`)},watch:!1}),o({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=l.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:n,disposeHttpServer:r}=await this.options.getHttpServer(e);oe(this.options.rootDir)&&this.options.logger.debug(`已清理旧缓存目录 node_modules/.previewjs`),this.options.logger.debug(`启动 Vite manager ...`),this.viteManager=new He({rootDir:this.options.rootDir,shadowHtmlFilePath:t.join(this.options.previewDirPath,`index.html`),reader:this.transformingReader,cacheDir:t.join(E(this.options.rootDir),`vite`),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:n,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug(`预览服务已就绪`),this.status={kind:`started`,onStop:r}})()},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}},Je=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}`}}}};async function Ye(e,t,n){let r=await N(e,t);for(let e of n)if(e.info&&await e.isCompatible(r,t))return e.info?.name;return null}async function Xe(e,t,n){let r=await N(e,t),i=[];for(let e of n){if(!e.info)continue;let n=e.info.name;try{i.push({name:n,compatible:await e.isCompatible(r,t),error:null})}catch(e){i.push({name:n,compatible:!1,error:String(e)})}}return i}const Ze=e(import.meta.url);process.on(`uncaughtException`,e=>{console.error(`Core 遇到未捕获的异常`,e)}),process.on(`unhandledRejection`,e=>{console.error(`Core 遇到未处理的 Promise 对象`,e)});async function Qe({rootDir:e,frameworkPlugin:s,logger:u=n(void 0,`core`),reader:f=o(),onServerStart:p=()=>Promise.resolve({})}){if(!s.info)throw Error(`framework plugin 与当前版本 ${T()} 不兼容. 请升级.`);if(s.info.apiVersion>5)throw Error(` ${s.info.name} 的 API 版本是 ${s.info.apiVersion}. 高于当前安装的 ${T()}, 请升级至最新版本.`);let m=await N(u,e);if(!await s.isCompatible(m,e))throw Error(` ${s.info.name} 与当前工作区的前端框架版本不兼容。`);u.info(`使用 ${s.info.name} 在目录: ${e} 中创建工作区`);let h=await s.create({rootDir:e,reader:f,logger:u,dependencies:m}),g=new Set,_={frameworkPluginName:s.info.name,frameworkPluginVersion:s.info.version,crawlFiles:h.crawlFiles,crawlProject:e=>M(u,_,h,e??{}),findGitignoredSourceFiles:()=>le(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,h.ignoredPaths),inspectScanCache:async()=>{let t=await O(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,{ignoredPaths:h.ignoredPaths});return se(e,s.info.name,s.info.version??`unknown`,t)},clearScanCache:()=>ce(e,s.info.name,s.info.version??`unknown`),typeAnalyzer:h.typeAnalyzer,rootDir:e,reader:f,startServer:async({asMiddleware:n,port:o,clientPort:m,onStop:v}={})=>{let y=o||await pe(3140),b=new Je(u);b.registerRPC(i.Analyze,async({previewableIds:n})=>{u.debug(`分析: ${n.join(`, `)}`);let i=await h.crawlFiles([...new Set(n.map(n=>t.join(e,r(n).filePath)))]);u.debug(`检测到 ${i.components.length} 个组件和 ${i.stories.length} 个story`);let o=[],s=Object.fromEntries(i.components.map(e=>[e.id,e])),c=Object.fromEntries(i.stories.map(e=>[e.id,e])),l={};for(let e of n){let t=s[e],n=c[e],i;if(t){let n;u.debug(`分析组件: ${e}`),{props:n,types:i}=await t.analyze(),o.push({kind:`component`,id:e,exported:t.exported,sourcePosition:t.sourcePosition,props:n})}else if(n){let t;n.associatedComponent?({props:t,types:i}=await n.associatedComponent.analyze(),u.debug(`分析 story: ${e} 的关联组件`)):(u.debug(`story: ${e} 没有关联的组件`),t=a,i={});let r=null;({args:r}=await n.analyze()),o.push({kind:`story`,id:e,sourcePosition:n.sourcePosition,associatedComponentId:n.associatedComponent?.id||null,props:t,args:r}),u.debug(`story args: ${JSON.stringify(r)}`)}else{let{filePath:t,name:n}=r(e);throw Error(`在 ${t} 中未找到组件 ${n}. `)}l={...l,...i}}return{previewables:o,types:l}}),b.registerRPC(i.GetInfo,async()=>({frameworkPlugin:s.info})),b.registerRPC(i.CrawlFiles,e=>M(u,_,h,e));let x=[c(),l.json(),async(e,t,n)=>{e.path.startsWith(`/api/`)?t.json(await b.handle(e.path.substr(5),e.body)):n()}];if(p){let{middlewares:e=[]}=await p({registerRPC:(e,t)=>b.registerRPC(e,t),workspace:_});x.push(...e)}let S=n?async e=>{let t=n.register(e);return{server:n.server,disposeHttpServer:async()=>{t()}}}:async e=>{u.debug(`启动 Express 服务器`);let t=l();t.use(e);let n=await new Promise(e=>{let n=t.listen(y,()=>{u.info(`${T()} 预览服务运行在 http://localhost:${y}.`),e(n)})}),r=d({server:n,gracefulTerminationTimeout:0});return{server:n,disposeHttpServer:async()=>{await r.terminate(),u.info(`${T()} 预览服务器已停止.`)}}},C=new qe({reader:f,rootDir:e,previewDirPath:t.join(t.dirname(t.dirname(Ze.resolve(`@cfp-studio/iframe`))),`preview`),frameworkPlugin:h,logger:u,middlewares:x,getHttpServer:S,port:y,clientPort:m});return await C.start(),g.add(C),{port:y,stop:async()=>{g.delete(C),await C.stop(),await v?.()}}},dispose:async()=>{await Promise.all([...g].map(e=>e.stop())),g.clear(),h.dispose()}};return _}function $e(e){let n=t.resolve(e);for(;n!==t.dirname(n);){if(u.existsSync(t.join(n,`package.json`)))return n;n=t.dirname(n)}return null}export{Qe as createWorkspace,N as extractPackageDependencies,Ye as findCompatiblePlugin,$e as findWorkspaceRoot,Xe as probeFrameworkCompatibility,R as toVitePath};
|
package/package.json
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
2
|
+
"name": "@cfp-studio/core",
|
|
3
|
+
"version": "1.0.13",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist"
|
|
7
|
+
],
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "./dist/index.mjs",
|
|
10
|
+
"types": "./dist/index.d.mts",
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@fwouts/vite-tsconfig-paths": "4.2.1",
|
|
13
|
+
"assert-never": "1.4.0",
|
|
14
|
+
"axios": "1.20.0",
|
|
15
|
+
"cors": "2.8.5",
|
|
16
|
+
"exclusive-promises": "1.0.3",
|
|
17
|
+
"express": "5.1.0",
|
|
18
|
+
"fs-extra": "11.3.2",
|
|
19
|
+
"globby": "14.1.0",
|
|
20
|
+
"html-escaper": "3.0.3",
|
|
21
|
+
"http-terminator": "3.2.0",
|
|
22
|
+
"pino": "9.11.0",
|
|
23
|
+
"pino-pretty": "13.1.1",
|
|
24
|
+
"tsconfig-paths": "4.2.0",
|
|
25
|
+
"typescript": "5.9.3",
|
|
26
|
+
"vite": "6.4.5",
|
|
27
|
+
"zod": "3.24.1",
|
|
28
|
+
"@cfp-studio/analyzer-api": "0.1.16",
|
|
29
|
+
"@cfp-studio/type-analyzer": "10.1.9",
|
|
30
|
+
"@cfp-studio/api": "16.1.2",
|
|
31
|
+
"@cfp-studio/iframe": "18.4.6",
|
|
32
|
+
"@cfp-studio/fiber-reader": "0.3.0",
|
|
33
|
+
"@cfp-studio/vfs": "2.1.8"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@rollup/plugin-alias": "5.1.1",
|
|
37
|
+
"@types/cors": "2.8.18",
|
|
38
|
+
"@types/express": "4.17.21",
|
|
39
|
+
"@types/fs-extra": "11.0.4",
|
|
40
|
+
"@types/html-escaper": "3.0.4",
|
|
41
|
+
"vitest": "5.0.5"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22.19.0"
|
|
45
|
+
},
|
|
46
|
+
"cfp": {
|
|
47
|
+
"domain": "web-preview",
|
|
48
|
+
"layer": "engine"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"prepublish": "pnpm release",
|
|
52
|
+
"build": "tsdown",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"release": "tsdown --minify",
|
|
55
|
+
"test": "vitest run",
|
|
56
|
+
"test:watch": "vitest watch",
|
|
57
|
+
"lint": "oxlint",
|
|
58
|
+
"format": "oxfmt --write ."
|
|
59
|
+
}
|
|
60
|
+
}
|