@cfp-studio/core 1.0.5 → 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/dist/index.mjs +7 -7
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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 from"node:url";import{globby as
|
|
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
|
|
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
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>
|
|
@@ -31,8 +31,8 @@ import{createRequire as e}from"node:module";import{decodePreviewableId as t}from
|
|
|
31
31
|
});
|
|
32
32
|
<\/script>
|
|
33
33
|
</head>
|
|
34
|
-
<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
|
|
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}
|
|
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{decodePreviewableId as t}from
|
|
|
40
40
|
}
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
|
-
`:null}}function
|
|
43
|
+
`:null}}function ye(){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 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
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{decodePreviewableId as t}from
|
|
|
123
123
|
function loadFreshWrapperModule() {
|
|
124
124
|
return import(/* @vite-ignore */ "/${n}?t=" + Date.now());
|
|
125
125
|
}
|
|
126
|
-
`}function be({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 B(e){let t=e;return t.match(/^[a-z]:/)&&(t=t[0]?.toUpperCase()+e.substring(1)),t.replace(/\\/g,`/`)}const V=`/@cfp-studio-virtual:`,H=`/@id/__x00__`,U=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]);function W(e){let t=e;return t.startsWith(V)&&(t=t.slice(21)),t.startsWith(`\0`)&&(t=t.slice(1)),t.startsWith(H)&&(t=t.slice(12)),[t,t!==e]}function xe(e){let{reader:t,rootDir:n}=e;return{name:`previewjs:virtual-fs`,resolveId:async(e,t)=>{let[n,i]=t?W(t):[null,!1];if(e.indexOf(`/node_modules/`)!==-1)return null;let[a]=W(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&&!U.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),V+e.replace(/\\/g,`/`))}return null},load:async t=>{let i=t;if(i.indexOf(`/node_modules/`)!==-1)return null;i.startsWith(V)&&(i=i.slice(21)),i.startsWith(`\0`)&&(i=i.slice(1)),i.startsWith(H)&&(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(!U.has(d))return l;let f=u.extname(t);return{code:!t.includes(`__previewjs_internal__`)&&(f===``||f===`.js`)?(await te(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(V)?{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=V+B(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[``,...U,...[...U].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 G=e(import.meta.url);function K(e){let t=Se(e);if(!t)return e;let n=u.join(u.dirname(u.dirname(t)),`src`,`index.ts`);return c.existsSync(n)?n:t}function Se(e){let t=[__dirname];try{t.push(u.dirname(G.resolve(`@cfp-studio/iframe/package.json`)))}catch{}for(let n of t)try{return G.resolve(e,{paths:[n]})}catch{}}const Ce=[`.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`],q=[`index`,`global`,`globals`,`style`,`styles`,`app`],J=[`css`,`sass`,`scss`,`less`,`styl`,`stylus`],we=q.flatMap(e=>J.map(t=>`${e}.${t}`)),Te=new Set([...j,...O,...Ce,...we,`vite.config.js`,`vite.config.ts`,`svelte.config.js`]);async function Y(e){return e?.kind===`starting`?e.promise:e}var Ee=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 Y(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 Y(this.#e);if(!r)return M(`Vite server is not running`);if(r.kind===`error`)return M(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 M(`${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,Q(this.options.logger)),n=await E(this.options.rootDir,`**/@(${q.join(`|`)}).@(${J.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=x(t)||null;if(e){a=Oe.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 S.loadConfigFromFile({command:`serve`,mode:`development`},void 0,this.options.rootDir),f=S.createLogger(Q(this.options.logger)),p=this.options.frameworkPlugin.viteConfig(await Z([...d?.config.plugins||[],...r.vite?.plugins||[]])),m=r.vite?.publicDir||d?.config.publicDir||p.publicDir||r.publicDir||`public`,h=De(this.options.reader,await Z([b({root:this.options.rootDir}),ye(),xe({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:[...r.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[ee(this.options.rootDir)],u.dirname(K(`@cfp-studio/fiber-reader`))],moduleGraph:()=>this.#e?.kind===`running`?this.#e.viteServer.moduleGraph:null,esbuildOptions:p.esbuild||{}}),ve(),_e(),I({readFile:e=>this.options.reader.read(e).then(e=>e?.kind===`file`?e.read():null)}),he(),be({rootDir:this.options.rootDir,publicDir:m}),p.plugins]));this.options.logger.debug(`Creating Vite server`);let g=await S.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:K(`@cfp-studio/fiber-reader`)},...X(r.vite?.resolve?.alias),...X(r.alias),...X(d?.config.resolve?.alias),...i,{find:/^~(.*)/,replacement:`${l}$1`},{find:`@`,replacement:l},...X(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 Y(this.#e);return t?.kind===`running`&&await t.viteServer.close(),e?this.start():this.#e=null})}async onFileChanged(e,t){let n=await Y(this.state);if(!n)return;if(!t.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(u.relative(this.options.rootDir,e)),Te.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(B(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 X(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({find:e,replacement:t})):[]}async function Z(e){let t=[];for(let n of await Promise.all(e))n&&(Array.isArray(n)?t.push(...await Z(n)):t.push(n));return t}function Q(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 De(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 Oe=w.object({compilerOptions:w.object({baseUrl:w.string().optional(),paths:w.record(w.array(w.string())).optional()}).optional()});var ke=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 v(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);ie(this.options.rootDir)&&this.options.logger.debug(`已清理旧缓存目录 node_modules/.previewjs`),this.options.logger.debug(`启动 Vite manager ...`),this.viteManager=new Ee({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 y.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}},Ae=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 je(e,t,n){let r=await A(e,t);for(let e of n)if(e.info&&await e.isCompatible(r))return e.info?.name;return null}const{pino:Me}=d,Ne=f,Pe=e(import.meta.url);process.on(`uncaughtException`,e=>{console.error(`Core 遇到未捕获的异常`,e)}),process.on(`unhandledRejection`,e=>{console.error(`Core 遇到未处理的 Promise 对象`,e)});async function Fe({rootDir:e,frameworkPlugin:a,logger:c=Me({level:process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase()||`warn`},Ne({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 A(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 Ae(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=>ae(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 ke({reader:d,rootDir:e,previewDirPath:u.join(u.dirname(u.dirname(Pe.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 Ie(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{Fe as createWorkspace,je as findCompatiblePlugin,Ie as findWorkspaceRoot,B 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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cfp-studio/core",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"typescript": "5.9.3",
|
|
26
26
|
"vite": "6.4.5",
|
|
27
27
|
"zod": "3.24.1",
|
|
28
|
-
"@cfp-studio/iframe": "18.2.0",
|
|
29
28
|
"@cfp-studio/fiber-reader": "0.1.0",
|
|
29
|
+
"@cfp-studio/analyzer-api": "0.1.12",
|
|
30
|
+
"@cfp-studio/iframe": "18.2.0",
|
|
30
31
|
"@cfp-studio/type-analyzer": "10.1.8",
|
|
31
32
|
"@cfp-studio/api": "16.1.1",
|
|
32
|
-
"@cfp-studio/vfs": "2.1.6"
|
|
33
|
-
"@cfp-studio/analyzer-api": "0.1.12"
|
|
33
|
+
"@cfp-studio/vfs": "2.1.6"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@rollup/plugin-alias": "5.1.1",
|