@chatbi-v/core 2.0.4 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/local-storage-adapter.d.ts +48 -0
- package/dist/adapters/scoped-storage-adapter.d.ts +45 -2
- package/dist/api/adapters/axios-adapter.d.ts +1 -1
- package/dist/api/engine.d.ts +22 -1
- package/dist/application/service-registry.d.ts +36 -13
- package/dist/components/PluginErrorBoundary.d.ts +23 -1
- package/dist/components/PluginSlot.d.ts +18 -7
- package/dist/components/SlotSkeletons.d.ts +15 -0
- package/dist/config-manager.d.ts +14 -10
- package/dist/domain/auto-loader.d.ts +19 -4
- package/dist/domain/models.d.ts +19 -11
- package/dist/domain/plugin-manager.d.ts +100 -44
- package/dist/domain/plugin-runtime.d.ts +40 -9
- package/dist/domain/plugin-sandbox.d.ts +15 -2
- package/dist/domain/storage-manager.d.ts +38 -10
- package/dist/hooks/use-plugin-loader.d.ts +20 -9
- package/dist/index.cjs +5 -5
- package/dist/index.mjs +5 -5
- package/dist/ports/api-port.d.ts +55 -26
- package/dist/ports/event-bus-port.d.ts +13 -11
- package/dist/ports/plugin-port.d.ts +113 -32
- package/dist/ports/storage-port.d.ts +34 -4
- package/dist/utils/logger.d.ts +22 -12
- package/package.json +5 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var me=Object.create;var K=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var xe=(g,e)=>()=>(g&&(e=g(g=0)),e);var ne=(g,e)=>{for(var t in e)K(g,t,{get:e[t],enumerable:!0})},ie=(g,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Pe.call(g,n)&&n!==t&&K(g,n,{get:()=>e[n],enumerable:!(r=ye(e,n))||r.enumerable});return g};var Y=(g,e,t)=>(t=g!=null?me(ve(g)):{},ie(e||!g||!g.__esModule?K(t,"default",{value:g,enumerable:!0}):t,g)),be=g=>ie(K({},"__esModule",{value:!0}),g);var ae={};ne(ae,{ConfigManager:()=>I,configManager:()=>m});var I,m,L=xe(()=>{"use strict";I=class{config=new Map;set(e,t){this.config.set(e,t)}get(e){return this.config.get(e)}merge(e){Object.keys(e).forEach(t=>{let r=this.config.get(t),n=e[t];r&&typeof r=="object"&&n&&typeof n=="object"?this.config.set(t,{...r,...n}):this.config.set(t,n)})}getAll(){return Object.fromEntries(this.config)}},m=new I});var Ge={};ne(Ge,{ApiEngine:()=>V,ApiProvider:()=>$e,AvatarSkeleton:()=>Oe,AxiosAdapter:()=>B,BasePlugin:()=>J,BlockSkeleton:()=>Ne,ConfigManager:()=>I,DefaultEventBus:()=>N,LocalStorageAdapter:()=>O,LogLevel:()=>Q,Logger:()=>k,PLUGIN_TYPES:()=>we,PluginErrorBoundary:()=>q,PluginManager:()=>_,PluginProvider:()=>Fe,PluginRuntime:()=>M,PluginSandbox:()=>F,PluginSlot:()=>ke,ProxySandbox:()=>j,SUCCESS_CODE:()=>te,ScopedStorageAdapter:()=>w,ServiceRegistry:()=>z,SidebarIconSkeleton:()=>Ie,Slot:()=>Ee,StatusBarItemSkeleton:()=>Le,StorageManager:()=>U,apiEngine:()=>qe,cleanUrlParams:()=>Be,configManager:()=>m,createLogger:()=>f,dateUtils:()=>We,definePlugin:()=>Re,isMockMode:()=>Ke,logger:()=>Ce,normalizeParams:()=>re,pluginManager:()=>h,resolveApiModules:()=>ze,resolvePluginRegistry:()=>ee,serviceRegistry:()=>T,useApi:()=>Te,usePluginLoader:()=>Ve,usePluginManager:()=>Ue,useStorageState:()=>He,version:()=>_e});module.exports=be(Ge);var we=["business","functional","view","theme","renderer","system"],Ee={Sidebar:"sidebar",SidebarPanel:"sidebar-panel",Header:"header",StatusBar:"status-bar",Settings:"settings",MessageRenderer:"message-renderer",MessageContentRenderer:"message-content-renderer",SidebarSystem:"sidebar-system",SidebarBottom:"sidebar-bottom",RootLayout:"root-layout",Custom:"custom"},J=class{get id(){return this.metadata.id}};function Re(g){return{...g,get id(){return this.metadata.id}}}var Q=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.NONE=4]="NONE",i))(Q||{}),k=class g{static level=1;prefix;constructor(e="App"){this.prefix=e}static setLevel(e){this.level=e,console.info(`[Logger] Global log level set to: ${Q[e]}`)}static getLevel(){return this.level}get debug(){return g.level<=0?console.debug.bind(console,`[${this.prefix}]`):A}get info(){return g.level<=1?console.info.bind(console,`[${this.prefix}]`):A}get warn(){return g.level<=2?console.warn.bind(console,`[${this.prefix}]`):A}get error(){return g.level<=3?console.error.bind(console,`[${this.prefix}]`):A}group(e,t=!1){g.level<=1&&(t?console.groupCollapsed(`[${this.prefix}] ${e}`):console.group(`[${this.prefix}] ${e}`))}get groupEnd(){return g.level<=1?console.groupEnd.bind(console):A}},A=()=>{},Ce=new k,f=g=>new k(g);var Z=f("ServiceRegistry"),z=class{services=new Map;listeners=new Map;register(e,t){this.services.has(e)&&Z.warn(`\u670D\u52A1 "${e}" \u5DF2\u5B58\u5728\uFF0C\u5C06\u88AB\u8986\u76D6`),this.services.set(e,t),Z.info(`\u670D\u52A1\u5DF2\u6CE8\u518C: ${e}`),this.listeners.has(e)&&(this.listeners.get(e).forEach(n=>n(t)),this.listeners.delete(e))}get(e){return this.services.get(e)}async waitFor(e,t=1e4){let r=this.services.get(e);return r||new Promise((n,i)=>{let o=null,a=s=>{o&&clearTimeout(o),n(s)};this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(a),t>0&&(o=setTimeout(()=>{let s=this.listeners.get(e);s&&(s.delete(a),s.size===0&&this.listeners.delete(e)),i(new Error(`\u7B49\u5F85\u670D\u52A1 "${e}" \u8D85\u65F6 (${t}ms)`))},t))})}has(e){return this.services.has(e)}unregister(e){this.services.delete(e),Z.info(`\u670D\u52A1\u5DF2\u6CE8\u9500: ${e}`)}clear(){this.services.clear(),this.listeners.clear()}},T=new z;var W=require("react"),oe=require("react/jsx-runtime"),se=(0,W.createContext)(null),$e=({api:g,children:e})=>(0,oe.jsx)(se.Provider,{value:g,children:e}),Te=()=>{let g=(0,W.useContext)(se);if(!g)throw new Error("useApi must be used within an ApiProvider");return g};L();var le=require("react");var O=class{prefix;constructor(e=""){this.prefix=e}getKey(e){return this.prefix?`${this.prefix}:${e}`:e}getOriginalKey(e){return this.prefix?e.startsWith(this.prefix+":")?e.slice(this.prefix.length+1):null:e}getItem(e){return localStorage.getItem(this.getKey(e))}setItem(e,t){localStorage.setItem(this.getKey(e),t)}removeItem(e){localStorage.removeItem(this.getKey(e))}clear(){if(!this.prefix){localStorage.clear();return}let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r&&r.startsWith(this.prefix+":")&&e.push(r)}e.forEach(t=>localStorage.removeItem(t))}get length(){if(!this.prefix)return localStorage.length;let e=0;for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r&&r.startsWith(this.prefix+":")&&e++}return e}key(e){if(!this.prefix)return localStorage.key(e);let t=0;for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n&&n.startsWith(this.prefix+":")){if(t===e)return this.getOriginalKey(n);t++}}return null}};L();var Me=f("EventBus"),N=class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e)?.push(t),()=>this.off(e,t)}off(e,t){let r=this.listeners.get(e);r&&this.listeners.set(e,r.filter(n=>n!==t))}emit(e,...t){let r=this.listeners.get(e);r&&r.forEach(n=>{try{n(...t)}catch(i){Me.error(`\u4E8B\u4EF6\u76D1\u542C\u5668\u5904\u7406\u9519\u8BEF (${e}):`,i)}})}once(e,t){let r=(...n)=>{t(...n),this.off(e,r)};this.on(e,r)}};var ge=f("ProxySandbox"),j=class{name;proxy;running=!1;updatedValueSet=new Set;effectPool={timeouts:new Set,intervals:new Set,listeners:new Map};globalContext;static globalWhitelist=["System","console","requestAnimationFrame","cancelAnimationFrame","location","history","navigator","document"];constructor(e,t=window){this.name=e,this.globalContext=t;let{fakeWindow:r,propertiesWithGetter:n}=this.createFakeWindow(t);this.patchGlobalEffects(r);let i=new Proxy(r,{set:(o,a,s)=>this.running?(this.updatedValueSet.add(a),o[a]=s,!0):(ge.warn(`${e} \u672A\u8FD0\u884C\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5C5E\u6027 '${String(a)}'`),!1),get:(o,a)=>{if(a===Symbol.unscopables)return;if(a==="window"||a==="self"||a==="globalThis")return this.proxy;if(a==="top"||a==="parent")return this.globalContext[a];let s=o[a];if(s!==void 0||this.updatedValueSet.has(a))return s;let l=this.globalContext[a];return typeof l=="function"&&!this.isConstructor(l)&&this.isNativeFunction(l)?l.bind(this.globalContext):l},has:(o,a)=>a in o||a in this.globalContext,defineProperty:(o,a,s)=>this.running?(this.updatedValueSet.add(a),Reflect.defineProperty(o,a,s)):!1});this.proxy=i}active(){this.running||(this.running=!0)}inactive(){this.running=!1,this.effectPool.timeouts.forEach(e=>this.globalContext.clearTimeout(e)),this.effectPool.timeouts.clear(),this.effectPool.intervals.forEach(e=>this.globalContext.clearInterval(e)),this.effectPool.intervals.clear(),this.effectPool.listeners.forEach((e,t)=>{e.forEach(({listener:r,options:n})=>{this.globalContext.removeEventListener(t,r,n)})}),this.effectPool.listeners.clear(),ge.debug(`${this.name} \u5DF2\u505C\u7528\uFF0C\u526F\u4F5C\u7528\u5DF2\u6E05\u9664\u3002`)}eval(e){let t=`
|
|
2
2
|
;(function(window, self, globalThis){
|
|
3
3
|
with(window) {
|
|
4
4
|
${e}
|
|
5
5
|
}
|
|
6
6
|
}).bind(window.proxy)(window.proxy, window.proxy, window.proxy);
|
|
7
|
-
`;return(0,eval)(t)}createFakeWindow(e){let t=new Map,r={};return Object.getOwnPropertyNames(e).forEach(n=>{let i=Object.getOwnPropertyDescriptor(e,n);i&&i.configurable}),{fakeWindow:r,propertiesWithGetter:t}}isConstructor(e){let t=e.prototype;return!!(t&&t.constructor===e&&Object.getOwnPropertyNames(t).length>0)}isNativeFunction(e){return e.toString().indexOf("[native code]")>-1}patchGlobalEffects(e){e.setTimeout=(t,r,...n)=>{let i=this.globalContext.setTimeout(t,r,...n);return this.effectPool.timeouts.add(i),i},e.clearTimeout=t=>{t&&(this.effectPool.timeouts.delete(t),this.globalContext.clearTimeout(t))},e.setInterval=(t,r,...n)=>{let i=this.globalContext.setInterval(t,r,...n);return this.effectPool.intervals.add(i),i},e.clearInterval=t=>{t&&(this.effectPool.intervals.delete(t),this.globalContext.clearInterval(t))},e.addEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t)||[];return i.push({listener:r,options:n}),this.effectPool.listeners.set(t,i),this.globalContext.addEventListener(t,r,n)},e.removeEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t);if(i){let a=i.findIndex(s=>s.listener===r&&s.options===n);a!==-1&&i.splice(a,1)}return this.globalContext.removeEventListener(t,r,n)}}};var K=class{pluginId;storageManager;constructor(e,t){this.pluginId=e,this.storageManager=t}get storage(){return this.storageManager.getContextStorage(this.pluginId)}get logger(){return f(`Plugin:${this.pluginId}`)}};var y=f("PluginRuntime"),A=class{plugin;context;storageSandbox;windowSandbox;isLoaded=!1;isMounted=!1;constructor(e,t,r){this.plugin=e,this.storageSandbox=new K(e.id,r),this.windowSandbox=new q(e.id),this.context={pluginId:e.id,api:t.api,events:t.events,storage:this.storageSandbox.storage,logger:this.storageSandbox.logger,window:this.windowSandbox.proxy,getService:n=>T.get(n),registerService:(n,i)=>T.register(`${e.id}.${n}`,i)}}async load(){if(!this.isLoaded){y.debug(`\u6B63\u5728\u52A0\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.metadata.api&&this.context.api&&typeof this.context.api.register=="function"&&(this.context.api.register(this.plugin.metadata.api),y.debug(`\u5DF2\u4E3A\u63D2\u4EF6 ${this.plugin.id} \u81EA\u52A8\u6CE8\u518C API \u914D\u7F6E`)),this.plugin.onLoad&&await this.plugin.onLoad(this.context),this.isLoaded=!0,y.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u52A0\u8F7D\u3002`)}catch(e){throw y.error(`\u63D2\u4EF6 ${this.plugin.id} \u52A0\u8F7D\u5931\u8D25:`,e),e}}}async mount(){if(this.isLoaded||await this.load(),!this.isMounted){y.debug(`\u6B63\u5728\u6302\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.windowSandbox.active(),this.plugin.onMount&&this.plugin.onMount(this.context),this.isMounted=!0,y.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u6302\u8F7D\u3002`)}catch(e){throw y.error(`\u63D2\u4EF6 ${this.plugin.id} \u6302\u8F7D\u5931\u8D25:`,e),e}}}async unmount(){if(this.isMounted){y.debug(`\u6B63\u5728\u5378\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.onUnmount&&this.plugin.onUnmount(this.context)}catch(e){y.error(`\u63D2\u4EF6 ${this.plugin.id} \u5378\u8F7D\u65F6\u51FA\u9519:`,e)}finally{this.windowSandbox.inactive(),this.isMounted=!1,y.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u5378\u8F7D\u3002`)}}}async destroy(){await this.unmount(),this.isLoaded=!1}get status(){return this.isMounted?"mounted":this.isLoaded?"loaded":"initial"}};var C=class{constructor(e,t){this.underlyingStorage=e;this.prefix=t}getKey(e){return this.prefix?`${this.prefix}:${e}`:e}getOriginalKey(e){return this.prefix?e.startsWith(this.prefix+":")?e.slice(this.prefix.length+1):null:e}getItem(e){return this.underlyingStorage.getItem(this.getKey(e))}setItem(e,t){this.underlyingStorage.setItem(this.getKey(e),t)}removeItem(e){this.underlyingStorage.removeItem(this.getKey(e))}clear(){if(!this.prefix){this.underlyingStorage.clear();return}let e=[];for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e.push(r)}e.forEach(t=>this.underlyingStorage.removeItem(t))}get length(){let e=0;for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e++}return e}key(e){let t=0;for(let r=0;r<this.underlyingStorage.length;r++){let n=this.underlyingStorage.key(r);if(n&&n.startsWith(this.prefix+":")){if(t===e)return this.getOriginalKey(n);t++}}return null}};F();var W=class{baseStorage;schemas=new Map;constructor(e){this.baseStorage=e}registerSchema(e,t){this.schemas.set(e,t)}validateKey(e,t,r="plugin"){let n=this.schemas.get(e);if(!n)return;let i=n.find(s=>s.key===t);if(!i){console.warn(`[Storage] Key "${t}" not defined in plugin "${e}" schema.`);return}let a=i.scope||"plugin";a!==r&&console.warn(`[Storage] Key "${t}" defined in scope "${a}" but accessed via "${r}".`)}getPluginStorage(e){return new C(this.baseStorage,`plugin:${e}`)}getSharedStorage(){return new C(this.baseStorage,"shared")}getSystemStorage(){return new C(this.baseStorage,"system")}getContextStorage(e){let t=this.getPluginStorage(e),r=this.getSharedStorage(),n=(i,a)=>({get:s=>{this.validateKey(e,s,a);try{let o=i.getItem(s);if(o!==null)try{return JSON.parse(o)}catch{return o}if(a==="plugin"){let c=h.get(e);if(c&&c[s]!==void 0)return c[s]}let l=this.schemas.get(e)?.find(c=>c.key===s);return l&&l.default!==void 0?l.default:null}catch(o){return console.warn(`[Storage] Failed to read key "${s}"`,o),null}},set:(s,o)=>{this.validateKey(e,s,a);try{i.setItem(s,JSON.stringify(o))}catch(l){console.warn(`[Storage] Failed to stringify key "${s}"`,l)}},remove:s=>{this.validateKey(e,s,a),i.removeItem(s)}});return{...n(t,"plugin"),shared:n(r,"shared")}}};var d=f("PluginManager"),J=class{eventBus=new D;storageManager;runtimes=new Map;plugins=new Map;routes=[];extensions=new Map;pluginStates={};listeners=new Set;sharedContext=null;utils={};constructor(e){this.storageManager=new W(e),this.loadStates(),this.subscribe(()=>{this.saveStates()})}loadStates(){try{let t=this.storageManager.getSystemStorage().getItem("plugin_states");t&&(this.pluginStates=JSON.parse(t),d.debug("\u4ECE\u7CFB\u7EDF\u5B58\u50A8\u4E2D\u52A0\u8F7D\u72B6\u6001:",this.pluginStates))}catch(e){d.error("\u52A0\u8F7D\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}saveStates(){try{this.storageManager.getSystemStorage().setItem("plugin_states",JSON.stringify(this.pluginStates)),d.debug("\u5DF2\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5230\u5B58\u50A8")}catch(e){d.error("\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getStorageManager(){return this.storageManager}notify(){this.listeners.forEach(e=>e())}getPlugins(){let e={system:0,theme:1,renderer:2,functional:3,business:4,view:5};return Array.from(this.plugins.values()).sort((t,r)=>{let n=e[t.metadata.type]??99,i=e[r.metadata.type]??99;if(n!==i)return n-i;let a=this.pluginStates[t.id]||{order:0},s=this.pluginStates[r.id]||{order:0};return a.order-s.order})}getPluginState(e){return this.pluginStates[e]||{enabled:!0,order:0}}isPluginEnabled(e){let t=this.pluginStates[e];return t?t.enabled:!0}togglePlugin(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};if(this.pluginStates[e]={...r,enabled:t},t){if(this.sharedContext){let n=this.plugins.get(e);if(n)try{let i=new A(n,this.sharedContext,this.storageManager);this.runtimes.set(e,i),i.mount()}catch(i){d.error(`\u542F\u7528\u63D2\u4EF6 ${e} \u5931\u8D25:`,i)}}}else{let n=this.runtimes.get(e);n&&(n.unmount(),this.runtimes.delete(e))}this.notify()}setPluginOrder(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};this.pluginStates[e]={...r,order:t},this.notify()}getUnifiedCapabilities(e){return this.plugins.get(e)?.metadata.capabilities||{}}updatePluginConfig(e,t,r){let n=h.get(e)||{};n[t]=r,h.set(e,n);try{this.storageManager.getContextStorage(e).set(t,r)}catch(i){d.warn("\u4FDD\u5B58\u914D\u7F6E\u5230\u5B58\u50A8\u5931\u8D25",i)}this.eventBus.emit("config:changed",{pluginId:e,key:t,value:r})}getPluginConfig(e,t){let r=h.get(e);return r?r[t]:void 0}getSystemConfig(e){let t=h.get("system");return t?t[e]:void 0}getService(e){return T.get(e)}getExtensions(e){let t=e,r=this.extensions.get(t)||[];return r=r.filter(n=>{let i=n._pluginId;return!i||this.isPluginEnabled(i)}),r.sort((n,i)=>(n.order||0)-(i.order||0))}getRoutes(){let e=[];return this.getPlugins().forEach(t=>{if(this.isPluginEnabled(t.id)&&t.metadata.routes){let r=h.get(t.id)||{};t.metadata.routes.forEach(n=>{e.push({...n,meta:{...n.meta,pluginId:t.id,config:r}})})}}),e}register(e,t=!0){if(!this.validatePlugin(e)){d.error(`\u63D2\u4EF6\u6CE8\u518C\u5931\u8D25: ${e?.id||"\u672A\u77E5"}`);return}if(this.plugins.has(e.id))return;let r=[...e.metadata.storage||[],...e.metadata.configuration?.map(o=>({key:o.key,type:o.type==="select"?"string":o.type,label:o.label,description:o.description,default:o.default,scope:"plugin"}))||[]];r.length>0&&this.storageManager.registerSchema(e.id,r),this.pluginStates[e.id]||(this.pluginStates[e.id]={enabled:!0,order:0});let n={},i={},a=this.storageManager.getPluginStorage(e.id);e.metadata.configuration&&e.metadata.configuration.forEach(o=>{o.default!==void 0&&(n[o.key]=o.default);try{let l=a.getItem(o.key);l!==null&&(i[o.key]=JSON.parse(l))}catch{}});let s={...n,...e.defaultConfig,...h.get(e.id)||{},...i};switch(h.set(e.id,s),e.metadata.type){case"business":this.handleBusinessPlugin(e);break;case"functional":this.handleFunctionalPlugin(e);break;case"view":this.handleViewPlugin(e);break;case"theme":this.handleThemePlugin(e);break;case"system":this.handleSystemPlugin(e);break;case"renderer":break;default:d.warn(`\u63D2\u4EF6 ${e.id} \u7C7B\u578B\u672A\u77E5: ${e.metadata.type}`);break}e.metadata.routes&&e.metadata.routes.length>0&&d.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u8DEF\u7531:`,e.metadata.routes),e.metadata.extensions&&e.metadata.extensions.length>0&&(e.metadata.extensions.forEach(o=>{let l=this.extensions.get(o.slot)||[];l.push({...o,_pluginId:e.id}),this.extensions.set(o.slot,l)}),d.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u6269\u5C55\u70B9`)),this.plugins.set(e.id,e),d.info(`\u63D2\u4EF6 ${e.id} \u5DF2\u6CE8\u518C\u4E3A ${e.metadata.type}\u3002`),t&&this.notify()}async initPlugins(e={}){this.sharedContext={...e,events:this.eventBus},this.plugins.forEach(r=>{if(this.isPluginEnabled(r.id)&&!this.runtimes.has(r.id)){let n=new A(r,this.sharedContext,this.storageManager);this.runtimes.set(r.id,n)}});let t=this.getSortedPluginIds();for(let r of t){let n=this.runtimes.get(r);if(n)try{console.log(`[PluginManager] invoking onLoad for ${r}`),await n.load(),console.log(`[PluginManager] onLoad completed for ${r}`)}catch(i){d.error(`\u63D2\u4EF6 ${r} \u52A0\u8F7D\u5931\u8D25:`,i)}}for(let r of t){let n=this.runtimes.get(r);if(n)try{await n.mount()}catch(i){d.error(`\u63D2\u4EF6 ${r} \u6302\u8F7D\u5931\u8D25:`,i)}}}getSortedPluginIds(){let e=Array.from(this.runtimes.keys()),t=new Set,r=[],n=new Set,i=o=>{if(t.has(o))return;if(n.has(o)){d.error(`\u5FAA\u73AF\u4F9D\u8D56\u68C0\u6D4B\u5230: ${o}`);return}n.add(o);let l=this.plugins.get(o);l?.metadata.dependencies&&l.metadata.dependencies.forEach(c=>{this.runtimes.has(c)&&i(c)}),n.delete(o),t.add(o),r.push(o)},a={system:100,functional:50,business:10};return[...e].sort((o,l)=>{let c=a[this.plugins.get(o)?.metadata.type||""]||0;return(a[this.plugins.get(l)?.metadata.type||""]||0)-c}).forEach(o=>i(o)),r}async loadPlugins(e,t){d.info("\u5F00\u59CB\u52A0\u8F7D\u63D2\u4EF6...");let r=Object.entries(t).map(async([a,s])=>{try{let o=await s(),l=e[a],c=this.instantiatePlugin(a,o,l);return c&&l&&h.set(c.id,l),c}catch(o){return d.error(`\u52A0\u8F7D\u672C\u5730\u63D2\u4EF6\u6A21\u5757 ${a} \u5931\u8D25:`,o),null}}),n=Object.entries(e).filter(([a,s])=>s.url&&!t[a]).map(async([a,s])=>{try{let o=await this.loadRemotePlugin(a,s.url,s);return o&&s&&h.set(o.id,s),o}catch(o){return d.error(`\u52A0\u8F7D\u5728\u7EBF\u63D2\u4EF6 ${a} \u5931\u8D25:`,o),null}});(await Promise.all([...r,...n])).forEach(a=>{a&&this.register(a,!1)}),this.notify(),d.info(`\u63D2\u4EF6\u52A0\u8F7D\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.plugins.size} \u4E2A\u63D2\u4EF6`)}async loadRemotePlugin(e,t,r){if(d.info(`\u6B63\u5728\u4ECE ${t} \u52A0\u8F7D\u8FDC\u7A0B\u63D2\u4EF6 ${e}...`),r?.format==="iife")return this.loadIIFEPlugin(e,t,r);try{let i=await new Function("specifier","return import(specifier)")(t);return this.instantiatePlugin(e,i,r)}catch{return d.warn(`ESM \u52A0\u8F7D\u5931\u8D25\uFF0C\u5C1D\u8BD5 IIFE \u52A0\u8F7D: ${e}`),this.loadIIFEPlugin(e,t,r)}}loadIIFEPlugin(e,t,r){return new Promise((n,i)=>{let a=document.createElement("script");a.src=t,a.onload=()=>{let s=e.replace(/[^a-zA-Z0-9]/g,"_"),o=window[s];o?n(this.instantiatePlugin(e,o,r)):i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u540E\u672A\u627E\u5230\u5168\u5C40\u53D8\u91CF ${s}`))},a.onerror=()=>i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: ${t}`)),document.head.appendChild(a)})}instantiatePlugin(e,t,r){let n=t.default;if(!n){let i=Object.keys(t).find(a=>a.endsWith("Plugin"));i&&(n=t[i])}if(!n&&typeof t=="object"&&t.id&&t.metadata&&(n=t),n){typeof n=="function"&&n.prototype&&d.warn(`\u63D2\u4EF6 ${e} \u4F7F\u7528\u4E86\u7C7B\u5B9A\u4E49\u6A21\u5F0F\u3002\u5EFA\u8BAE\u7EDF\u4E00\u4F7F\u7528 definePlugin() \u5DE5\u5382\u6A21\u5F0F\u4EE5\u6D88\u9664\u6B67\u4E49\u5E76\u7B80\u5316\u4EE3\u7801\u3002`);let a=typeof n=="function"?new n:n;if(!(e.includes("/")&&(e.includes(".ts")||e.includes(".tsx")))&&e&&a.metadata&&a.metadata.id!==e&&(a.metadata.id=e),!a.id&&a.metadata?.id)try{a.id=a.metadata.id}catch{}return r&&(a.defaultConfig={...a.defaultConfig,...r}),a}return d.warn(`\u6A21\u5757 ${e} \u672A\u5BFC\u51FA\u6709\u6548\u7684\u63D2\u4EF6\u5165\u53E3`),null}validatePlugin(e){return!(!e.id||!e.metadata)}handleBusinessPlugin(e){}handleFunctionalPlugin(e){}handleViewPlugin(e){}handleThemePlugin(e){}handleSystemPlugin(e){}},m=new J(new B);var v=require("react/jsx-runtime"),Ne=({slot:g,props:e={},className:t,style:r,renderItem:n,skeleton:i,fallback:a})=>{let[,s]=(0,R.useState)({});(0,R.useEffect)(()=>m.subscribe(()=>{s({})}),[]);let o=m.getExtensions(g),l=m.getSystemConfig("title")?{title:m.getSystemConfig("title"),logo:m.getSystemConfig("logo"),version:m.getSystemConfig("version")}:void 0,c=(0,R.useMemo)(()=>({...e,systemConfig:l}),[e,l]),u=(0,R.useMemo)(()=>o.map((p,x)=>{let _=p.component,P=p.meta?.key||`${p.slot}-${p.order||0}-${x}`;return{key:P,extension:p,component:(0,v.jsx)(U,{pluginId:`extension-${P}`,children:(0,v.jsx)(_,{...c})},P)}}),[o,c]);return u.length===0?a?(0,v.jsx)(v.Fragment,{children:a}):i?(0,v.jsx)("div",{className:`plugin-slot plugin-slot-${g} plugin-slot-skeleton ${t||""}`,style:r,children:i}):null:u.length===1&&g==="root-layout"&&!t&&!r&&!n?(0,v.jsx)(v.Fragment,{children:u[0].component}):(0,v.jsx)("div",{className:`plugin-slot plugin-slot-${g} ${t||""}`,style:r,children:n?u.map((p,x)=>n(p,x)):u.map(p=>p.component)})};var b=require("react/jsx-runtime"),je=({expanded:g=!1})=>(0,b.jsxs)("div",{className:`flex items-center transition-all duration-300 relative
|
|
8
|
-
${g?"w-full":"w-12 justify-center"} px-3 h-11 rounded-xl`,children:[(0,b.jsx)("div",{className:"w-6 h-6 bg-slate-200 dark:bg-white/10 rounded-lg shrink-0 animate-pulse"}),g&&(0,b.jsx)("div",{className:"ml-3 flex-1 h-4 bg-slate-200 dark:bg-white/10 rounded animate-pulse"})]}),
|
|
7
|
+
`;return(0,eval)(t)}createFakeWindow(e){let t=new Map,r={};return Object.getOwnPropertyNames(e).forEach(n=>{let i=Object.getOwnPropertyDescriptor(e,n);i&&i.configurable}),{fakeWindow:r,propertiesWithGetter:t}}isConstructor(e){let t=e.prototype;return!!(t&&t.constructor===e&&Object.getOwnPropertyNames(t).length>0)}isNativeFunction(e){return e.toString().indexOf("[native code]")>-1}patchGlobalEffects(e){e.setTimeout=(t,r,...n)=>{let i=this.globalContext.setTimeout(t,r,...n);return this.effectPool.timeouts.add(i),i},e.clearTimeout=t=>{t&&(this.effectPool.timeouts.delete(t),this.globalContext.clearTimeout(t))},e.setInterval=(t,r,...n)=>{let i=this.globalContext.setInterval(t,r,...n);return this.effectPool.intervals.add(i),i},e.clearInterval=t=>{t&&(this.effectPool.intervals.delete(t),this.globalContext.clearInterval(t))},e.addEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t)||[];return i.push({listener:r,options:n}),this.effectPool.listeners.set(t,i),this.globalContext.addEventListener(t,r,n)},e.removeEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t);if(i){let o=i.findIndex(a=>a.listener===r&&a.options===n);o!==-1&&i.splice(o,1)}return this.globalContext.removeEventListener(t,r,n)}}};var F=class{pluginId;storageManager;constructor(e,t){this.pluginId=e,this.storageManager=t}get storage(){return this.storageManager.getContextStorage(this.pluginId)}get logger(){return f(`Plugin:${this.pluginId}`)}};var S=f("PluginRuntime"),M=class{plugin;context;storageSandbox;windowSandbox;isLoaded=!1;isMounted=!1;error=null;constructor(e,t,r){this.plugin=e,this.storageSandbox=new F(e.id,r),this.windowSandbox=new j(e.id),this.context={pluginId:e.id,api:t.api,events:t.events,storage:this.storageSandbox.storage,logger:this.storageSandbox.logger,window:this.windowSandbox.proxy,getService:n=>T.get(n),registerService:(n,i)=>T.register(`${e.id}.${n}`,i)}}async load(){if(!this.isLoaded){S.debug(`\u6B63\u5728\u52A0\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.metadata.api&&this.context.api&&typeof this.context.api.register=="function"&&(this.context.api.register(this.plugin.metadata.api),S.debug(`\u5DF2\u4E3A\u63D2\u4EF6 ${this.plugin.id} \u81EA\u52A8\u6CE8\u518C API \u914D\u7F6E`)),this.plugin.onLoad&&await this.plugin.onLoad(this.context),this.isLoaded=!0,this.error=null,S.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u52A0\u8F7D\u3002`)}catch(e){this.error=e instanceof Error?e:new Error(String(e)),S.error(`\u63D2\u4EF6 ${this.plugin.id} \u52A0\u8F7D\u5931\u8D25:`,e)}}}async mount(){if(this.isLoaded||await this.load(),!this.isMounted){S.debug(`\u6B63\u5728\u6302\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.windowSandbox.active(),this.plugin.onMount&&this.plugin.onMount(this.context),this.isMounted=!0,this.error=null,S.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u6302\u8F7D\u3002`)}catch(e){this.error=e instanceof Error?e:new Error(String(e)),S.error(`\u63D2\u4EF6 ${this.plugin.id} \u6302\u8F7D\u5931\u8D25:`,e)}}}async unmount(){if(this.isMounted){S.debug(`\u6B63\u5728\u5378\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.onUnmount&&this.plugin.onUnmount(this.context)}catch(e){S.error(`\u63D2\u4EF6 ${this.plugin.id} \u5378\u8F7D\u65F6\u51FA\u9519:`,e)}finally{this.windowSandbox.inactive(),this.isMounted=!1,this.error=null,S.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u5378\u8F7D\u3002`)}}}async destroy(){await this.unmount(),this.isLoaded=!1,this.error=null}_setError(e){this.error=e}getError(){return this.error}get status(){return this.error?"error":this.isMounted?"mounted":this.isLoaded?"loaded":"initial"}};var w=class{constructor(e,t){this.underlyingStorage=e;this.prefix=t}getKey(e){return this.prefix?`${this.prefix}:${e}`:e}getOriginalKey(e){return this.prefix?e.startsWith(this.prefix+":")?e.slice(this.prefix.length+1):null:e}getItem(e){return this.underlyingStorage.getItem(this.getKey(e))}setItem(e,t){this.underlyingStorage.setItem(this.getKey(e),t)}removeItem(e){this.underlyingStorage.removeItem(this.getKey(e))}clear(){if(!this.prefix){this.underlyingStorage.clear();return}let e=[];for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e.push(r)}e.forEach(t=>this.underlyingStorage.removeItem(t))}get length(){let e=0;for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e++}return e}key(e){let t=0;for(let r=0;r<this.underlyingStorage.length;r++){let n=this.underlyingStorage.key(r);if(n&&n.startsWith(this.prefix+":")){if(t===e)return this.getOriginalKey(n);t++}}return null}};L();var U=class{baseStorage;schemas=new Map;memoryCache=new Map;constructor(e){this.baseStorage=e}registerSchema(e,t){this.schemas.set(e,t)}validateKey(e,t,r="plugin"){let n=this.schemas.get(e);if(!n)return;let i=n.find(a=>a.key===t);if(!i){console.warn(`[Storage] Key "${t}" not defined in plugin "${e}" schema.`);return}let o=i.scope||"plugin";o!==r&&console.warn(`[Storage] Key "${t}" defined in scope "${o}" but accessed via "${r}".`)}getPluginStorage(e){return new w(this.baseStorage,`plugin:${e}`)}getSharedStorage(){return new w(this.baseStorage,"shared")}getSystemStorage(){return new w(this.baseStorage,"system")}getContextStorage(e){let t=this.getPluginStorage(e),r=this.getSharedStorage(),n=(i,o)=>{let a=o==="plugin"?`plugin:${e}:`:"shared:";return{get:s=>{this.validateKey(e,s,o);let l=`${a}${s}`;try{if(this.memoryCache.has(l))return this.memoryCache.get(l);let c=i.getItem(s);if(c!==null){let u;try{u=JSON.parse(c)}catch{u=c}return this.memoryCache.set(l,u),u}if(o==="plugin"){let u=m.get(e);if(u&&u[s]!==void 0)return u[s]}let d=this.schemas.get(e)?.find(u=>u.key===s);return d&&d.default!==void 0?d.default:null}catch(c){return console.warn(`[Storage] Failed to read key "${s}"`,c),null}},set:(s,l)=>{this.validateKey(e,s,o);let c=`${a}${s}`;try{this.memoryCache.set(c,l),i.setItem(s,JSON.stringify(l))}catch(d){console.warn(`[Storage] Failed to stringify key "${s}"`,d)}},remove:s=>{this.validateKey(e,s,o);let l=`${a}${s}`;this.memoryCache.delete(l),i.removeItem(s)}}};return{...n(t,"plugin"),shared:n(r,"shared")}}};var p=f("PluginManager"),_=class{eventBus=new N;storageManager;runtimes=new Map;plugins=new Map;routes=[];extensions=new Map;pluginStates={};listeners=new Set;slotListeners=new Map;memoizedExtensions=new Map;memoizedRoutes=null;sharedContext=null;utils={};constructor(e){this.storageManager=new U(e),this.loadStates(),this.subscribe(()=>{this.saveStates()})}loadStates(){try{let t=this.storageManager.getSystemStorage().getItem("plugin_states");t&&(this.pluginStates=JSON.parse(t),p.debug("\u4ECE\u7CFB\u7EDF\u5B58\u50A8\u4E2D\u52A0\u8F7D\u72B6\u6001:",this.pluginStates))}catch(e){p.error("\u52A0\u8F7D\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}saveStates(){try{this.storageManager.getSystemStorage().setItem("plugin_states",JSON.stringify(this.pluginStates)),p.debug("\u5DF2\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5230\u5B58\u50A8")}catch(e){p.error("\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}subscribe(e,t){if(t){let r=String(t);return this.slotListeners.has(r)||this.slotListeners.set(r,new Set),this.slotListeners.get(r).add(e),()=>{this.slotListeners.get(r)?.delete(e)}}else return this.listeners.add(e),()=>{this.listeners.delete(e)}}getStorageManager(){return this.storageManager}notify(e){e?this.memoizedExtensions.delete(String(e)):(this.memoizedExtensions.clear(),this.memoizedRoutes=null),this.listeners.forEach(t=>t()),e?this.slotListeners.get(String(e))?.forEach(t=>t()):this.slotListeners.forEach(t=>t.forEach(r=>r()))}getPlugins(){let e={system:0,theme:1,renderer:2,functional:3,business:4,view:5};return Array.from(this.plugins.values()).sort((t,r)=>{let n=e[t.metadata.type]??99,i=e[r.metadata.type]??99;if(n!==i)return n-i;let o=this.pluginStates[t.id]||{order:0},a=this.pluginStates[r.id]||{order:0};return o.order-a.order})}getPluginState(e){return this.pluginStates[e]||{enabled:!0,order:0}}isPluginEnabled(e){let t=this.pluginStates[e];return t?t.enabled:!0}togglePlugin(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};if(this.pluginStates[e]={...r,enabled:t},t){if(this.sharedContext){let n=this.plugins.get(e);if(n)try{let i=new M(n,this.sharedContext,this.storageManager);this.runtimes.set(e,i),i.mount()}catch(i){p.error(`\u542F\u7528\u63D2\u4EF6 ${e} \u5931\u8D25:`,i)}}}else{let n=this.runtimes.get(e);n&&(n.unmount(),this.runtimes.delete(e))}this.notify()}setPluginOrder(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};this.pluginStates[e]={...r,order:t},this.notify()}getPluginRuntimeStatus(e){let t=this.runtimes.get(e);return t?t.status:"initial"}getPluginError(e){let t=this.runtimes.get(e);return t?t.getError():null}reportPluginError(e,t){let r=this.runtimes.get(e);r&&(r._setError?.(t),this.notify())}getUnifiedCapabilities(e){return this.plugins.get(e)?.metadata.capabilities||{}}updatePluginConfig(e,t,r){let n=m.get(e)||{};n[t]=r,m.set(e,n);try{this.storageManager.getContextStorage(e).set(t,r)}catch(i){p.warn("\u4FDD\u5B58\u914D\u7F6E\u5230\u5B58\u50A8\u5931\u8D25",i)}this.eventBus.emit("config:changed",{pluginId:e,key:t,value:r})}getPluginConfig(e,t){let r=m.get(e);return r?r[t]:void 0}getSystemConfig(e){let t=m.get("system");return t?t[e]:void 0}getService(e){return T.get(e)}getExtensions(e){let t=String(e);if(this.memoizedExtensions.has(t))return this.memoizedExtensions.get(t);let r=e,n=this.extensions.get(r)||[];n=n.filter(o=>{let a=o._pluginId;return!a||this.isPluginEnabled(a)});let i=n.sort((o,a)=>(o.order||0)-(a.order||0));return this.memoizedExtensions.set(t,i),i}getRoutes(){if(this.memoizedRoutes)return this.memoizedRoutes;let e=[];return this.getPlugins().forEach(t=>{if(this.isPluginEnabled(t.id)&&t.metadata.routes){let r=m.get(t.id)||{};t.metadata.routes.forEach(n=>{e.push({...n,meta:{...n.meta,pluginId:t.id,config:r}})})}}),this.memoizedRoutes=e,e}register(e,t=!0){if(!this.validatePlugin(e)){p.error(`\u63D2\u4EF6\u6CE8\u518C\u5931\u8D25: ${e?.id||"\u672A\u77E5"}`);return}if(this.plugins.has(e.id))return;let r=[...e.metadata.storage||[],...e.metadata.configuration?.map(s=>({key:s.key,type:s.type==="select"?"string":s.type,label:s.label,description:s.description,default:s.default,scope:"plugin"}))||[]];r.length>0&&this.storageManager.registerSchema(e.id,r),this.pluginStates[e.id]||(this.pluginStates[e.id]={enabled:!0,order:0});let n={},i={},o=this.storageManager.getPluginStorage(e.id);e.metadata.configuration&&e.metadata.configuration.forEach(s=>{s.default!==void 0&&(n[s.key]=s.default);try{let l=o.getItem(s.key);l!==null&&(i[s.key]=JSON.parse(l))}catch{}});let a={...n,...e.defaultConfig,...m.get(e.id)||{},...i};switch(m.set(e.id,a),e.metadata.type){case"business":this.handleBusinessPlugin(e);break;case"functional":this.handleFunctionalPlugin(e);break;case"view":this.handleViewPlugin(e);break;case"theme":this.handleThemePlugin(e);break;case"system":this.handleSystemPlugin(e);break;case"renderer":break;default:p.warn(`\u63D2\u4EF6 ${e.id} \u7C7B\u578B\u672A\u77E5: ${e.metadata.type}`);break}e.metadata.routes&&e.metadata.routes.length>0&&p.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u8DEF\u7531:`,e.metadata.routes),e.metadata.extensions&&e.metadata.extensions.length>0&&(e.metadata.extensions.forEach(s=>{let l=this.extensions.get(s.slot)||[];l.push({...s,_pluginId:e.id}),this.extensions.set(s.slot,l)}),p.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u6269\u5C55\u70B9`)),this.plugins.set(e.id,e),p.info(`\u63D2\u4EF6 ${e.id} \u5DF2\u6CE8\u518C\u4E3A ${e.metadata.type}\u3002`),t&&this.notify()}async initPlugins(e={}){this.sharedContext={...e,events:this.eventBus},this.plugins.forEach(r=>{if(this.isPluginEnabled(r.id)&&!this.runtimes.has(r.id)){let n=new M(r,this.sharedContext,this.storageManager);this.runtimes.set(r.id,n)}});let t=this.getSortedPluginIds();for(let r of t){let n=this.runtimes.get(r);if(n)try{console.log(`[PluginManager] invoking onLoad for ${r}`),await n.load(),console.log(`[PluginManager] onLoad completed for ${r}`)}catch(i){p.error(`\u63D2\u4EF6 ${r} \u52A0\u8F7D\u5931\u8D25:`,i)}}for(let r of t){let n=this.runtimes.get(r);if(n)try{await n.mount()}catch(i){p.error(`\u63D2\u4EF6 ${r} \u6302\u8F7D\u5931\u8D25:`,i)}}}getSortedPluginIds(){let e=Array.from(this.runtimes.keys()),t=new Set,r=[],n=new Set,i=s=>{if(t.has(s))return;if(n.has(s)){p.error(`\u5FAA\u73AF\u4F9D\u8D56\u68C0\u6D4B\u5230: ${s}`);return}n.add(s);let l=this.plugins.get(s);l?.metadata.dependencies&&l.metadata.dependencies.forEach(c=>{this.runtimes.has(c)&&i(c)}),n.delete(s),t.add(s),r.push(s)},o={system:100,functional:50,business:10};return[...e].sort((s,l)=>{let c=o[this.plugins.get(s)?.metadata.type||""]||0;return(o[this.plugins.get(l)?.metadata.type||""]||0)-c}).forEach(s=>i(s)),r}async loadPlugins(e,t){p.info("\u5F00\u59CB\u52A0\u8F7D\u63D2\u4EF6...");let r=Object.entries(t).map(async([o,a])=>{try{let s=await a(),l=e[o],c=this.instantiatePlugin(o,s,l);return c&&l&&m.set(c.id,l),c}catch(s){return p.error(`\u52A0\u8F7D\u672C\u5730\u63D2\u4EF6\u6A21\u5757 ${o} \u5931\u8D25:`,s),null}}),n=Object.entries(e).filter(([o,a])=>a.url&&!t[o]).map(async([o,a])=>{try{let s=await this.loadRemotePlugin(o,a.url,a);return s&&a&&m.set(s.id,a),s}catch(s){return p.error(`\u52A0\u8F7D\u5728\u7EBF\u63D2\u4EF6 ${o} \u5931\u8D25:`,s),null}});(await Promise.all([...r,...n])).forEach(o=>{o&&this.register(o,!1)}),this.notify(),p.info(`\u63D2\u4EF6\u52A0\u8F7D\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.plugins.size} \u4E2A\u63D2\u4EF6`)}async loadRemotePlugin(e,t,r){if(p.info(`\u6B63\u5728\u4ECE ${t} \u52A0\u8F7D\u8FDC\u7A0B\u63D2\u4EF6 ${e}...`),r?.format==="iife")return this.loadIIFEPlugin(e,t,r);try{let i=await new Function("specifier","return import(specifier)")(t);return this.instantiatePlugin(e,i,r)}catch{return p.warn(`ESM \u52A0\u8F7D\u5931\u8D25\uFF0C\u5C1D\u8BD5 IIFE \u52A0\u8F7D: ${e}`),this.loadIIFEPlugin(e,t,r)}}loadIIFEPlugin(e,t,r){return new Promise((n,i)=>{let o=document.createElement("script");o.src=t,o.onload=()=>{let a=e.replace(/[^a-zA-Z0-9]/g,"_"),s=window[a];s?n(this.instantiatePlugin(e,s,r)):i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u540E\u672A\u627E\u5230\u5168\u5C40\u53D8\u91CF ${a}`))},o.onerror=()=>i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: ${t}`)),document.head.appendChild(o)})}instantiatePlugin(e,t,r){let n=t.default;if(!n){let i=Object.keys(t).find(o=>o.endsWith("Plugin"));i&&(n=t[i])}if(!n&&typeof t=="object"&&t.id&&t.metadata&&(n=t),n){typeof n=="function"&&n.prototype&&p.warn(`\u63D2\u4EF6 ${e} \u4F7F\u7528\u4E86\u7C7B\u5B9A\u4E49\u6A21\u5F0F\u3002\u5EFA\u8BAE\u7EDF\u4E00\u4F7F\u7528 definePlugin() \u5DE5\u5382\u6A21\u5F0F\u4EE5\u6D88\u9664\u6B67\u4E49\u5E76\u7B80\u5316\u4EE3\u7801\u3002`);let o=typeof n=="function"?new n:n;if(!(e.includes("/")&&(e.includes(".ts")||e.includes(".tsx")))&&e&&o.metadata&&o.metadata.id!==e&&(o.metadata.id=e),!o.id&&o.metadata?.id)try{o.id=o.metadata.id}catch{}return r&&(o.defaultConfig={...o.defaultConfig,...r}),o}return p.warn(`\u6A21\u5757 ${e} \u672A\u5BFC\u51FA\u6709\u6548\u7684\u63D2\u4EF6\u5165\u53E3`),null}validatePlugin(e){return!(!e.id||!e.metadata)}handleBusinessPlugin(e){}handleFunctionalPlugin(e){}handleViewPlugin(e){}handleThemePlugin(e){}handleSystemPlugin(e){}},h=new _(new O);var ce=require("react/jsx-runtime"),Ae=f("PluginErrorBoundary"),q=class extends le.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){Ae.error(`\u63D2\u4EF6 ${this.props.pluginId||"\u672A\u77E5"} \u6E32\u67D3\u53D1\u751F\u9519\u8BEF:`,e,t),this.props.pluginId&&(console.warn(`[PluginError] \u63D2\u4EF6 "${this.props.pluginId}" \u6E32\u67D3\u5931\u8D25\u3002\u60A8\u53EF\u4EE5\u5728\u63D2\u4EF6\u7BA1\u7406\u9762\u677F\u67E5\u770B\u8BE6\u7EC6\u4FE1\u606F\u3002`),h.reportPluginError(this.props.pluginId,e))}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:this.props.silent?null:(0,ce.jsx)("div",{className:"plugin-error-placeholder hidden","data-plugin-id":this.props.pluginId,"data-error":this.state.error?.message}):this.props.children}};var E=require("react");var v=require("react/jsx-runtime"),ke=({slot:g,props:e={},className:t="",style:r,renderItem:n,skeleton:i,fallback:o})=>{let[,a]=(0,E.useState)({});(0,E.useEffect)(()=>h.subscribe(()=>{a({})},g),[g]);let s=h.getExtensions(g),l=h.getSystemConfig("title")?{title:h.getSystemConfig("title"),logo:h.getSystemConfig("logo"),version:h.getSystemConfig("version")}:void 0,c=(0,E.useMemo)(()=>({...e,systemConfig:l}),[e,l]),d=(0,E.useMemo)(()=>s.map((u,x)=>{let y=u.component,$=u.meta?.key||`${u.slot}-${u.order||0}-${x}`;return{key:$,extension:u,component:(0,v.jsx)(q,{pluginId:u._pluginId,children:(0,v.jsx)(y,{...c})},$)}}),[s,c]);return d.length===0?o?(0,v.jsx)(v.Fragment,{children:o}):i?(0,v.jsx)("div",{className:`plugin-slot plugin-slot-${g} plugin-slot-skeleton ${t||""}`,style:r,children:i}):null:d.length===1&&g==="root-layout"&&!t&&!r&&!n?(0,v.jsx)(v.Fragment,{children:d[0].component}):(0,v.jsx)("div",{className:`plugin-slot plugin-slot-${g} ${t||""}`,style:r,children:n?d.map((u,x)=>n(u,x)):d.map(u=>u.component)})};var b=require("react/jsx-runtime"),Ie=({expanded:g=!1})=>(0,b.jsxs)("div",{className:`flex items-center transition-all duration-300 relative
|
|
8
|
+
${g?"w-full":"w-12 justify-center"} px-3 h-11 rounded-xl`,children:[(0,b.jsx)("div",{className:"w-6 h-6 bg-slate-200 dark:bg-white/10 rounded-lg shrink-0 animate-pulse"}),g&&(0,b.jsx)("div",{className:"ml-3 flex-1 h-4 bg-slate-200 dark:bg-white/10 rounded animate-pulse"})]}),Le=()=>(0,b.jsx)("div",{className:"h-4 w-16 bg-slate-200 dark:bg-white/10 rounded animate-pulse"}),Oe=()=>(0,b.jsx)("div",{className:"w-10 h-10 rounded-full bg-slate-200 dark:bg-white/10 animate-pulse"}),Ne=({className:g})=>(0,b.jsx)("div",{className:`bg-slate-200 dark:bg-white/10 rounded animate-pulse ${g||"w-full h-full"}`});var X=f("AutoLoader"),je=[{pathSegment:"@chatbi-plugins",idPrefix:"@chatbi-v/plugin"},{pathSegment:"@chatbi-apps",idPrefix:"@chatbi-v/app"},{pathSegment:"packages/plugins",idPrefix:"@chatbi-v/plugin"},{pathSegment:"packages/apps",idPrefix:"@chatbi-v/app"}],ee=g=>{let{modules:e,rules:t=je}=g,r={},n=t.map(i=>{let o=i.pathSegment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{...i,regex:new RegExp(`${o}/([^/]+)/src/index`)}});for(let i in e)try{let o=null;for(let a of n){let s=i.match(a.regex);if(s&&s[1]){o=`${a.idPrefix}-${s[1]}`,X.info(`\u89E3\u6790\u8DEF\u5F84\u6210\u529F: ${i} -> ${o}`);break}}o?r[o]=e[i]:X.warn(`\u65E0\u6CD5\u4ECE\u8DEF\u5F84\u89E3\u6790\u63D2\u4EF6 ID: ${i}\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u7B26\u5408\u547D\u540D\u7EA6\u5B9A\u3002`)}catch(o){X.error(`\u89E3\u6790\u63D2\u4EF6\u8DEF\u5F84\u5931\u8D25: ${i}`,o)}return r};var te="000000";var H=require("react"),de=require("react/jsx-runtime"),ue=(0,H.createContext)(null),Fe=({manager:g,children:e})=>(0,de.jsx)(ue.Provider,{value:g,children:e}),Ue=()=>{let g=(0,H.useContext)(ue);if(!g)throw new Error("usePluginManager must be used within a PluginProvider");return g};var pe=Y(require("axios")),B=class{client;constructor(e="/api",t=1e4){this.client=pe.default.create({baseURL:e,timeout:t}),this.client.interceptors.response.use(r=>r,r=>Promise.reject(r))}async request(e){return this.client.request(e)}async stream(e,t,r){let{onMessage:n,onError:i,onFinish:o}=t;try{let a=await this.client.request({...e,headers:{"Cache-Control":"no-cache",Pragma:"no-cache",...e.headers},adapter:async u=>{let x=this.client.getUri(u),y=await fetch(x,{method:u.method?.toUpperCase(),headers:u.headers,body:u.data?typeof u.data=="string"?u.data:JSON.stringify(u.data):void 0,signal:u.signal});return{data:y,status:y.status,statusText:y.statusText,headers:y.headers,config:u}}}),s=a instanceof Response?a:a.data;if(t.onResponse&&await t.onResponse(a))return;if(!(s instanceof Response))throw new Error("\u6D41\u5F0F\u8BF7\u6C42\u5931\u8D25\uFF1A\u672A\u80FD\u83B7\u53D6\u5230\u539F\u59CB\u54CD\u5E94\u6D41\uFF0C\u8BF7\u68C0\u67E5 Axios \u54CD\u5E94\u62E6\u622A\u5668\u662F\u5426\u6B63\u786E\u5904\u7406\u4E86 Response \u5BF9\u8C61\u3002");if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);if(!s.body)throw new Error("\u54CD\u5E94\u4F53\u4E3A\u7A7A");let l=s.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:u,value:x}=await l.read();if(u)break;d+=c.decode(x,{stream:!0});let y=d.split(`
|
|
9
9
|
|
|
10
|
-
`);
|
|
10
|
+
`);d=y.pop()||"";for(let $ of y)n&&n($+`
|
|
11
11
|
|
|
12
|
-
`)}
|
|
12
|
+
`)}d&&n&&n(d),o&&o()}catch(a){i&&i(a)}}};var R=f("ApiEngine"),V=class{adapter;config={};interceptors=[];constructor(e){this.adapter=e||new B}registerInterceptor(e){this.interceptors.push(e)}unregisterInterceptor(e){this.interceptors=this.interceptors.filter(t=>t!==e)}useAdapter(e){this.adapter=e}register(e){R.info("\u6B63\u5728\u6CE8\u518C API \u914D\u7F6E:",Object.keys(e)),this.config={...this.config,...e}}getEndpoint(e,t){return this.config[e]?.[t]}async call(e,t,r,n={}){let i=this.getEndpoint(e,t);if(!i)return R.warn(`\u672A\u627E\u5230 API \u5B9A\u4E49: ${e}.${t} (\u5F53\u524D\u5DF2\u6CE8\u518C\u6A21\u5757: ${Object.keys(this.config).join(", ")})`),Promise.resolve(void 0);let o=await this.prepareRequestConfig(i,r,n),a;try{a=await this.adapter.request(o,i)}catch(c){if(c.response)a=c.response;else throw c}if(await this.applyResponseInterceptors(a,o)){R.info("\u8BF7\u6C42\u88AB\u62E6\u622A\u5668\u52AB\u6301:",e,t);return}this.checkHttpStatus(a);let l=this.extractResponseData(a);return this.handleBusinessError(l,i,e,t),l}async stream(e,t,r,n={}){let i=this.getEndpoint(e,t);if(!i){R.warn(`\u672A\u627E\u5230 API \u5B9A\u4E49: ${e}.${t}\uFF0C\u8DF3\u8FC7\u6D41\u5F0F\u8BF7\u6C42\u3002`);return}if(!this.adapter.stream){R.warn("\u5F53\u524D API \u9002\u914D\u5668\u4E0D\u652F\u6301\u6D41\u5F0F\u4F20\u8F93\u3002");return}let o=await this.prepareRequestConfig(i,r,n),a={onMessage:n.onMessage,onError:n.onError,onFinish:n.onFinish};try{await this.adapter.stream(o,{...a,onResponse:async s=>await this.applyResponseInterceptors(s,o)?(R.info("\u6D41\u5F0F\u8BF7\u6C42\u88AB\u62E6\u622A\u5668\u52AB\u6301:",e,t),o.signal instanceof AbortController&&o.signal.abort(),!0):(this.checkHttpStatus(s),!1)},i)}catch(s){if(a.onError)a.onError(s);else throw s}}async prepareRequestConfig(e,t,r){let n=e.url,i=r.params||{};n=n.replace(/:([a-zA-Z0-9_]+)/g,(s,l)=>i[l]!==void 0?String(i[l]):t&&typeof t=="object"&&t[l]!==void 0?String(t[l]):`:${l}`);let o=e.method,a={...r,url:n,method:o};return o==="GET"||o==="DELETE"?a.params=t:a.data=t,this.applyRequestInterceptors(a)}async applyRequestInterceptors(e){let t=e;for(let r of this.interceptors)r.interceptRequest&&(t=await r.interceptRequest(t));return t}async applyResponseInterceptors(e,t){if(this.interceptors.length===0)return!1;let r=this.createInterceptorContext(e,t);for(let n of this.interceptors)if(n.interceptResponse&&await n.interceptResponse(r))return!0;return!1}checkHttpStatus(e){if(e&&e.status&&(e.status<200||e.status>=300)){let t=this.extractResponseData(e);if(!this.isBaseResponse(t))throw new Error(`Request failed with status ${e.status}`)}}extractResponseData(e){return this.isAxiosResponse(e)?e.data:e}handleBusinessError(e,t,r,n){if(!this.isBaseResponse(e))return;let i=e,o=String(i.code);if(!(o===te||o==="200"||o==="0")&&(t.errorStrategy||"reject")==="reject")throw R.error(`API \u8BF7\u6C42\u4E1A\u52A1\u9519\u8BEF (${r}.${n}):`,i.message),new Error(i.message||`Request failed with code ${o}`)}isBaseResponse(e){return e&&typeof e=="object"&&"code"in e&&("message"in e||"data"in e)}isAxiosResponse(e){return e&&typeof e=="object"&&"data"in e&&"status"in e&&"headers"in e}createInterceptorContext(e,t){return e&&typeof e=="object"&&"status"in e&&"headers"in e?{response:e,status:e.status,headers:e.headers,data:e.data,config:t}:{response:e,status:200,headers:{},data:e,config:t}}},qe=new V;function re(g="last"){if(typeof window>"u")return new URLSearchParams;let{search:e,hash:t}=window.location,r=new URLSearchParams(e),n=new URLSearchParams(t.split("?")[1]||""),i=[];r.forEach((a,s)=>i.push([s,a,"search"])),n.forEach((a,s)=>i.push([s,a,"hash"]));let o=new Map;return g==="first"?i.forEach(([a,s])=>{o.has(a)||o.set(a,s)}):g==="last"?i.forEach(([a,s])=>o.set(a,s)):g==="search"?(i.forEach(([a,s,l])=>{l==="search"&&o.set(a,s)}),n.forEach((a,s)=>{o.has(s)||o.set(s,a)})):g==="hash"&&(i.forEach(([a,s,l])=>{l==="hash"&&o.set(a,s)}),r.forEach((a,s)=>{o.has(s)||o.set(s,a)})),new URLSearchParams(Array.from(o.entries()))}function Be(g){if(typeof window>"u")return"";let{pathname:e,search:t,hash:r}=window.location,n=new URLSearchParams(t);g.forEach(u=>n.delete(u));let i=n.toString(),o=r.split("?"),a=o[0],s=o[1]||"",l=new URLSearchParams(s);g.forEach(u=>l.delete(u));let c=l.toString(),d=a+(c?"?"+c:"");return e+(i?"?"+i:"")+d}var De=(g,e)=>{let t=JSON.parse(JSON.stringify(g));return Object.keys(e).forEach(r=>{t[r]&&(t[r]={...t[r],...e[r]})}),t};function Ke(){let g=typeof process<"u"&&process.env.VITE_USE_MOCK==="true"||typeof window<"u"&&window.VITE_USE_MOCK==="true";if(typeof window<"u"){let t=re().get("mock");if(t==="true")return!0;if(t==="false")return!1}return g}function ze(g,e={}){let t={},r=n=>(n.split("/").pop()||"").replace(/\.mock\.(ts|js|tsx|jsx|json)$/,"").replace(/\.(ts|js|tsx|jsx|json)$/,"");return Object.entries(g).forEach(([n,i])=>{if(n.includes(".mock."))return;let o=r(n);if(!o||!i.default)return;let a=i.default,s=Object.entries(e).find(([l])=>r(l)===o&&l.includes(".mock."));if(s){let l=s[1],c=l.default||l;c&&(a=De(a,c))}t[o]=a}),t}var P=Y(require("dayjs")),fe=Y(require("dayjs/plugin/relativeTime")),sr=require("dayjs/locale/zh-cn");P.default.extend(fe.default);P.default.locale("zh-cn");var We={formatDate(g){return(0,P.default)(g).format("YYYY-MM-DD")},formatTime(g){return(0,P.default)(g).format("HH:mm:ss")},formatDateTime(g){return(0,P.default)(g).format("YYYY-MM-DD HH:mm:ss")},now(){return(0,P.default)().valueOf()},fromNow(g){return(0,P.default)(g).fromNow()},dayjs:P.default};var _e="1.0.0";var D=require("react");function He(g,e,t={}){let{defaultValue:r,scope:n="plugin"}=t,i=h.getStorageManager(),o=(0,D.useCallback)(()=>{let c=i.getContextStorage(g);return n==="shared"?c.shared:c},[g,n,i]),[a,s]=(0,D.useState)(()=>{try{if(typeof window>"u")return r;let d=o().get(e);return d!==null?d:r}catch(c){return console.warn(`[useStorageState] Error reading key "${e}"`,c),r}}),l=(0,D.useCallback)(c=>{try{let d=c instanceof Function?c(a):c;s(d),o().set(e,d)}catch(d){console.warn(`[useStorageState] Error setting key "${e}":`,d)}},[e,a,o]);return[a,l]}var C=require("react");var G=f("PluginLoader"),Ve=g=>{let[e,t]=(0,C.useState)(!1),[r,n]=(0,C.useState)(0),i=(0,C.useRef)(!1);return(0,C.useEffect)(()=>{let o=h.subscribe(()=>{G.debug("Plugin state changed, refreshing UI..."),n(s=>s+1)});return(async()=>{if(!(i.current||e)){i.current=!0;try{let{discoveryRules:s=[],modules:l={},registry:c={},pluginConfigs:d,sharedContext:u={},baseUrl:x=window.location.origin}=g;G.info("Starting to load plugins...");let $={...Object.keys(l).length>0?ee({modules:l,rules:s.length>0?s:void 0}):{},...c};if(g.systemConfig){let{configManager:he}=await Promise.resolve().then(()=>(L(),ae));he.set("system",g.systemConfig)}await h.loadPlugins(d,$),await h.initPlugins(u),t(!0),G.info("Plugins loaded successfully")}catch(s){G.error("Failed to load plugins:",s)}finally{i.current=!1}}})(),()=>{o()}},[]),{pluginsLoaded:e,pluginVersion:r}};0&&(module.exports={ApiEngine,ApiProvider,AvatarSkeleton,AxiosAdapter,BasePlugin,BlockSkeleton,ConfigManager,DefaultEventBus,LocalStorageAdapter,LogLevel,Logger,PLUGIN_TYPES,PluginErrorBoundary,PluginManager,PluginProvider,PluginRuntime,PluginSandbox,PluginSlot,ProxySandbox,SUCCESS_CODE,ScopedStorageAdapter,ServiceRegistry,SidebarIconSkeleton,Slot,StatusBarItemSkeleton,StorageManager,apiEngine,cleanUrlParams,configManager,createLogger,dateUtils,definePlugin,isMockMode,logger,normalizeParams,pluginManager,resolveApiModules,resolvePluginRegistry,serviceRegistry,useApi,usePluginLoader,usePluginManager,useStorageState,version});
|
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as be,b as m}from"./chunk-O74KYN5N.mjs";var we=["business","functional","view","theme","renderer","system"],Ee={Sidebar:"sidebar",SidebarPanel:"sidebar-panel",Header:"header",StatusBar:"status-bar",Settings:"settings",MessageRenderer:"message-renderer",MessageContentRenderer:"message-content-renderer",SidebarSystem:"sidebar-system",SidebarBottom:"sidebar-bottom",RootLayout:"root-layout",Custom:"custom"},z=class{get id(){return this.metadata.id}};function Re(g){return{...g,get id(){return this.metadata.id}}}var W=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.NONE=4]="NONE",i))(W||{}),M=class g{static level=1;prefix;constructor(e="App"){this.prefix=e}static setLevel(e){this.level=e,console.info(`[Logger] Global log level set to: ${W[e]}`)}static getLevel(){return this.level}get debug(){return g.level<=0?console.debug.bind(console,`[${this.prefix}]`):R}get info(){return g.level<=1?console.info.bind(console,`[${this.prefix}]`):R}get warn(){return g.level<=2?console.warn.bind(console,`[${this.prefix}]`):R}get error(){return g.level<=3?console.error.bind(console,`[${this.prefix}]`):R}group(e,t=!1){g.level<=1&&(t?console.groupCollapsed(`[${this.prefix}] ${e}`):console.group(`[${this.prefix}] ${e}`))}get groupEnd(){return g.level<=1?console.groupEnd.bind(console):R}},R=()=>{},$e=new M,f=g=>new M(g);var U=f("ServiceRegistry"),q=class{services=new Map;listeners=new Map;register(e,t){this.services.has(e)&&U.warn(`\u670D\u52A1 "${e}" \u5DF2\u5B58\u5728\uFF0C\u5C06\u88AB\u8986\u76D6`),this.services.set(e,t),U.info(`\u670D\u52A1\u5DF2\u6CE8\u518C: ${e}`),this.listeners.has(e)&&(this.listeners.get(e).forEach(n=>n(t)),this.listeners.delete(e))}get(e){return this.services.get(e)}async waitFor(e,t=1e4){let r=this.services.get(e);return r||new Promise((n,i)=>{let o=null,a=s=>{o&&clearTimeout(o),n(s)};this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(a),t>0&&(o=setTimeout(()=>{let s=this.listeners.get(e);s&&(s.delete(a),s.size===0&&this.listeners.delete(e)),i(new Error(`\u7B49\u5F85\u670D\u52A1 "${e}" \u8D85\u65F6 (${t}ms)`))},t))})}has(e){return this.services.has(e)}unregister(e){this.services.delete(e),U.info(`\u670D\u52A1\u5DF2\u6CE8\u9500: ${e}`)}clear(){this.services.clear(),this.listeners.clear()}},C=new q;import{createContext as re,useContext as ne}from"react";import{jsx as ie}from"react/jsx-runtime";var _=re(null),Le=({api:g,children:e})=>ie(_.Provider,{value:g,children:e}),Oe=()=>{let g=ne(_);if(!g)throw new Error("useApi must be used within an ApiProvider");return g};import{Component as oe}from"react";var A=class{prefix;constructor(e=""){this.prefix=e}getKey(e){return this.prefix?`${this.prefix}:${e}`:e}getOriginalKey(e){return this.prefix?e.startsWith(this.prefix+":")?e.slice(this.prefix.length+1):null:e}getItem(e){return localStorage.getItem(this.getKey(e))}setItem(e,t){localStorage.setItem(this.getKey(e),t)}removeItem(e){localStorage.removeItem(this.getKey(e))}clear(){if(!this.prefix){localStorage.clear();return}let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r&&r.startsWith(this.prefix+":")&&e.push(r)}e.forEach(t=>localStorage.removeItem(t))}get length(){if(!this.prefix)return localStorage.length;let e=0;for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r&&r.startsWith(this.prefix+":")&&e++}return e}key(e){if(!this.prefix)return localStorage.key(e);let t=0;for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n&&n.startsWith(this.prefix+":")){if(t===e)return this.getOriginalKey(n);t++}}return null}};var se=f("EventBus"),k=class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e)?.push(t),()=>this.off(e,t)}off(e,t){let r=this.listeners.get(e);r&&this.listeners.set(e,r.filter(n=>n!==t))}emit(e,...t){let r=this.listeners.get(e);r&&r.forEach(n=>{try{n(...t)}catch(i){se.error(`\u4E8B\u4EF6\u76D1\u542C\u5668\u5904\u7406\u9519\u8BEF (${e}):`,i)}})}once(e,t){let r=(...n)=>{t(...n),this.off(e,r)};this.on(e,r)}};var H=f("ProxySandbox"),I=class{name;proxy;running=!1;updatedValueSet=new Set;effectPool={timeouts:new Set,intervals:new Set,listeners:new Map};globalContext;static globalWhitelist=["System","console","requestAnimationFrame","cancelAnimationFrame","location","history","navigator","document"];constructor(e,t=window){this.name=e,this.globalContext=t;let{fakeWindow:r,propertiesWithGetter:n}=this.createFakeWindow(t);this.patchGlobalEffects(r);let i=new Proxy(r,{set:(o,a,s)=>this.running?(this.updatedValueSet.add(a),o[a]=s,!0):(H.warn(`${e} \u672A\u8FD0\u884C\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5C5E\u6027 '${String(a)}'`),!1),get:(o,a)=>{if(a===Symbol.unscopables)return;if(a==="window"||a==="self"||a==="globalThis")return this.proxy;if(a==="top"||a==="parent")return this.globalContext[a];let s=o[a];if(s!==void 0||this.updatedValueSet.has(a))return s;let l=this.globalContext[a];return typeof l=="function"&&!this.isConstructor(l)&&this.isNativeFunction(l)?l.bind(this.globalContext):l},has:(o,a)=>a in o||a in this.globalContext,defineProperty:(o,a,s)=>this.running?(this.updatedValueSet.add(a),Reflect.defineProperty(o,a,s)):!1});this.proxy=i}active(){this.running||(this.running=!0)}inactive(){this.running=!1,this.effectPool.timeouts.forEach(e=>this.globalContext.clearTimeout(e)),this.effectPool.timeouts.clear(),this.effectPool.intervals.forEach(e=>this.globalContext.clearInterval(e)),this.effectPool.intervals.clear(),this.effectPool.listeners.forEach((e,t)=>{e.forEach(({listener:r,options:n})=>{this.globalContext.removeEventListener(t,r,n)})}),this.effectPool.listeners.clear(),H.debug(`${this.name} \u5DF2\u505C\u7528\uFF0C\u526F\u4F5C\u7528\u5DF2\u6E05\u9664\u3002`)}eval(e){let t=`
|
|
2
2
|
;(function(window, self, globalThis){
|
|
3
3
|
with(window) {
|
|
4
4
|
${e}
|
|
5
5
|
}
|
|
6
6
|
}).bind(window.proxy)(window.proxy, window.proxy, window.proxy);
|
|
7
|
-
`;return(0,eval)(t)}createFakeWindow(e){let t=new Map,r={};return Object.getOwnPropertyNames(e).forEach(n=>{let i=Object.getOwnPropertyDescriptor(e,n);i&&i.configurable}),{fakeWindow:r,propertiesWithGetter:t}}isConstructor(e){let t=e.prototype;return!!(t&&t.constructor===e&&Object.getOwnPropertyNames(t).length>0)}isNativeFunction(e){return e.toString().indexOf("[native code]")>-1}patchGlobalEffects(e){e.setTimeout=(t,r,...n)=>{let i=this.globalContext.setTimeout(t,r,...n);return this.effectPool.timeouts.add(i),i},e.clearTimeout=t=>{t&&(this.effectPool.timeouts.delete(t),this.globalContext.clearTimeout(t))},e.setInterval=(t,r,...n)=>{let i=this.globalContext.setInterval(t,r,...n);return this.effectPool.intervals.add(i),i},e.clearInterval=t=>{t&&(this.effectPool.intervals.delete(t),this.globalContext.clearInterval(t))},e.addEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t)||[];return i.push({listener:r,options:n}),this.effectPool.listeners.set(t,i),this.globalContext.addEventListener(t,r,n)},e.removeEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t);if(i){let a=i.findIndex(s=>s.listener===r&&s.options===n);a!==-1&&i.splice(a,1)}return this.globalContext.removeEventListener(t,r,n)}}};var U=class{pluginId;storageManager;constructor(e,t){this.pluginId=e,this.storageManager=t}get storage(){return this.storageManager.getContextStorage(this.pluginId)}get logger(){return f(`Plugin:${this.pluginId}`)}};var y=f("PluginRuntime"),A=class{plugin;context;storageSandbox;windowSandbox;isLoaded=!1;isMounted=!1;constructor(e,t,r){this.plugin=e,this.storageSandbox=new U(e.id,r),this.windowSandbox=new j(e.id),this.context={pluginId:e.id,api:t.api,events:t.events,storage:this.storageSandbox.storage,logger:this.storageSandbox.logger,window:this.windowSandbox.proxy,getService:n=>k.get(n),registerService:(n,i)=>k.register(`${e.id}.${n}`,i)}}async load(){if(!this.isLoaded){y.debug(`\u6B63\u5728\u52A0\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.metadata.api&&this.context.api&&typeof this.context.api.register=="function"&&(this.context.api.register(this.plugin.metadata.api),y.debug(`\u5DF2\u4E3A\u63D2\u4EF6 ${this.plugin.id} \u81EA\u52A8\u6CE8\u518C API \u914D\u7F6E`)),this.plugin.onLoad&&await this.plugin.onLoad(this.context),this.isLoaded=!0,y.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u52A0\u8F7D\u3002`)}catch(e){throw y.error(`\u63D2\u4EF6 ${this.plugin.id} \u52A0\u8F7D\u5931\u8D25:`,e),e}}}async mount(){if(this.isLoaded||await this.load(),!this.isMounted){y.debug(`\u6B63\u5728\u6302\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.windowSandbox.active(),this.plugin.onMount&&this.plugin.onMount(this.context),this.isMounted=!0,y.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u6302\u8F7D\u3002`)}catch(e){throw y.error(`\u63D2\u4EF6 ${this.plugin.id} \u6302\u8F7D\u5931\u8D25:`,e),e}}}async unmount(){if(this.isMounted){y.debug(`\u6B63\u5728\u5378\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.onUnmount&&this.plugin.onUnmount(this.context)}catch(e){y.error(`\u63D2\u4EF6 ${this.plugin.id} \u5378\u8F7D\u65F6\u51FA\u9519:`,e)}finally{this.windowSandbox.inactive(),this.isMounted=!1,y.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u5378\u8F7D\u3002`)}}}async destroy(){await this.unmount(),this.isLoaded=!1}get status(){return this.isMounted?"mounted":this.isLoaded?"loaded":"initial"}};var w=class{constructor(e,t){this.underlyingStorage=e;this.prefix=t}getKey(e){return this.prefix?`${this.prefix}:${e}`:e}getOriginalKey(e){return this.prefix?e.startsWith(this.prefix+":")?e.slice(this.prefix.length+1):null:e}getItem(e){return this.underlyingStorage.getItem(this.getKey(e))}setItem(e,t){this.underlyingStorage.setItem(this.getKey(e),t)}removeItem(e){this.underlyingStorage.removeItem(this.getKey(e))}clear(){if(!this.prefix){this.underlyingStorage.clear();return}let e=[];for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e.push(r)}e.forEach(t=>this.underlyingStorage.removeItem(t))}get length(){let e=0;for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e++}return e}key(e){let t=0;for(let r=0;r<this.underlyingStorage.length;r++){let n=this.underlyingStorage.key(r);if(n&&n.startsWith(this.prefix+":")){if(t===e)return this.getOriginalKey(n);t++}}return null}};var B=class{baseStorage;schemas=new Map;constructor(e){this.baseStorage=e}registerSchema(e,t){this.schemas.set(e,t)}validateKey(e,t,r="plugin"){let n=this.schemas.get(e);if(!n)return;let i=n.find(s=>s.key===t);if(!i){console.warn(`[Storage] Key "${t}" not defined in plugin "${e}" schema.`);return}let a=i.scope||"plugin";a!==r&&console.warn(`[Storage] Key "${t}" defined in scope "${a}" but accessed via "${r}".`)}getPluginStorage(e){return new w(this.baseStorage,`plugin:${e}`)}getSharedStorage(){return new w(this.baseStorage,"shared")}getSystemStorage(){return new w(this.baseStorage,"system")}getContextStorage(e){let t=this.getPluginStorage(e),r=this.getSharedStorage(),n=(i,a)=>({get:s=>{this.validateKey(e,s,a);try{let o=i.getItem(s);if(o!==null)try{return JSON.parse(o)}catch{return o}if(a==="plugin"){let c=m.get(e);if(c&&c[s]!==void 0)return c[s]}let l=this.schemas.get(e)?.find(c=>c.key===s);return l&&l.default!==void 0?l.default:null}catch(o){return console.warn(`[Storage] Failed to read key "${s}"`,o),null}},set:(s,o)=>{this.validateKey(e,s,a);try{i.setItem(s,JSON.stringify(o))}catch(l){console.warn(`[Storage] Failed to stringify key "${s}"`,l)}},remove:s=>{this.validateKey(e,s,a),i.removeItem(s)}});return{...n(t,"plugin"),shared:n(r,"shared")}}};var d=f("PluginManager"),V=class{eventBus=new F;storageManager;runtimes=new Map;plugins=new Map;routes=[];extensions=new Map;pluginStates={};listeners=new Set;sharedContext=null;utils={};constructor(e){this.storageManager=new B(e),this.loadStates(),this.subscribe(()=>{this.saveStates()})}loadStates(){try{let t=this.storageManager.getSystemStorage().getItem("plugin_states");t&&(this.pluginStates=JSON.parse(t),d.debug("\u4ECE\u7CFB\u7EDF\u5B58\u50A8\u4E2D\u52A0\u8F7D\u72B6\u6001:",this.pluginStates))}catch(e){d.error("\u52A0\u8F7D\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}saveStates(){try{this.storageManager.getSystemStorage().setItem("plugin_states",JSON.stringify(this.pluginStates)),d.debug("\u5DF2\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5230\u5B58\u50A8")}catch(e){d.error("\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getStorageManager(){return this.storageManager}notify(){this.listeners.forEach(e=>e())}getPlugins(){let e={system:0,theme:1,renderer:2,functional:3,business:4,view:5};return Array.from(this.plugins.values()).sort((t,r)=>{let n=e[t.metadata.type]??99,i=e[r.metadata.type]??99;if(n!==i)return n-i;let a=this.pluginStates[t.id]||{order:0},s=this.pluginStates[r.id]||{order:0};return a.order-s.order})}getPluginState(e){return this.pluginStates[e]||{enabled:!0,order:0}}isPluginEnabled(e){let t=this.pluginStates[e];return t?t.enabled:!0}togglePlugin(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};if(this.pluginStates[e]={...r,enabled:t},t){if(this.sharedContext){let n=this.plugins.get(e);if(n)try{let i=new A(n,this.sharedContext,this.storageManager);this.runtimes.set(e,i),i.mount()}catch(i){d.error(`\u542F\u7528\u63D2\u4EF6 ${e} \u5931\u8D25:`,i)}}}else{let n=this.runtimes.get(e);n&&(n.unmount(),this.runtimes.delete(e))}this.notify()}setPluginOrder(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};this.pluginStates[e]={...r,order:t},this.notify()}getUnifiedCapabilities(e){return this.plugins.get(e)?.metadata.capabilities||{}}updatePluginConfig(e,t,r){let n=m.get(e)||{};n[t]=r,m.set(e,n);try{this.storageManager.getContextStorage(e).set(t,r)}catch(i){d.warn("\u4FDD\u5B58\u914D\u7F6E\u5230\u5B58\u50A8\u5931\u8D25",i)}this.eventBus.emit("config:changed",{pluginId:e,key:t,value:r})}getPluginConfig(e,t){let r=m.get(e);return r?r[t]:void 0}getSystemConfig(e){let t=m.get("system");return t?t[e]:void 0}getService(e){return k.get(e)}getExtensions(e){let t=e,r=this.extensions.get(t)||[];return r=r.filter(n=>{let i=n._pluginId;return!i||this.isPluginEnabled(i)}),r.sort((n,i)=>(n.order||0)-(i.order||0))}getRoutes(){let e=[];return this.getPlugins().forEach(t=>{if(this.isPluginEnabled(t.id)&&t.metadata.routes){let r=m.get(t.id)||{};t.metadata.routes.forEach(n=>{e.push({...n,meta:{...n.meta,pluginId:t.id,config:r}})})}}),e}register(e,t=!0){if(!this.validatePlugin(e)){d.error(`\u63D2\u4EF6\u6CE8\u518C\u5931\u8D25: ${e?.id||"\u672A\u77E5"}`);return}if(this.plugins.has(e.id))return;let r=[...e.metadata.storage||[],...e.metadata.configuration?.map(o=>({key:o.key,type:o.type==="select"?"string":o.type,label:o.label,description:o.description,default:o.default,scope:"plugin"}))||[]];r.length>0&&this.storageManager.registerSchema(e.id,r),this.pluginStates[e.id]||(this.pluginStates[e.id]={enabled:!0,order:0});let n={},i={},a=this.storageManager.getPluginStorage(e.id);e.metadata.configuration&&e.metadata.configuration.forEach(o=>{o.default!==void 0&&(n[o.key]=o.default);try{let l=a.getItem(o.key);l!==null&&(i[o.key]=JSON.parse(l))}catch{}});let s={...n,...e.defaultConfig,...m.get(e.id)||{},...i};switch(m.set(e.id,s),e.metadata.type){case"business":this.handleBusinessPlugin(e);break;case"functional":this.handleFunctionalPlugin(e);break;case"view":this.handleViewPlugin(e);break;case"theme":this.handleThemePlugin(e);break;case"system":this.handleSystemPlugin(e);break;case"renderer":break;default:d.warn(`\u63D2\u4EF6 ${e.id} \u7C7B\u578B\u672A\u77E5: ${e.metadata.type}`);break}e.metadata.routes&&e.metadata.routes.length>0&&d.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u8DEF\u7531:`,e.metadata.routes),e.metadata.extensions&&e.metadata.extensions.length>0&&(e.metadata.extensions.forEach(o=>{let l=this.extensions.get(o.slot)||[];l.push({...o,_pluginId:e.id}),this.extensions.set(o.slot,l)}),d.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u6269\u5C55\u70B9`)),this.plugins.set(e.id,e),d.info(`\u63D2\u4EF6 ${e.id} \u5DF2\u6CE8\u518C\u4E3A ${e.metadata.type}\u3002`),t&&this.notify()}async initPlugins(e={}){this.sharedContext={...e,events:this.eventBus},this.plugins.forEach(r=>{if(this.isPluginEnabled(r.id)&&!this.runtimes.has(r.id)){let n=new A(r,this.sharedContext,this.storageManager);this.runtimes.set(r.id,n)}});let t=this.getSortedPluginIds();for(let r of t){let n=this.runtimes.get(r);if(n)try{console.log(`[PluginManager] invoking onLoad for ${r}`),await n.load(),console.log(`[PluginManager] onLoad completed for ${r}`)}catch(i){d.error(`\u63D2\u4EF6 ${r} \u52A0\u8F7D\u5931\u8D25:`,i)}}for(let r of t){let n=this.runtimes.get(r);if(n)try{await n.mount()}catch(i){d.error(`\u63D2\u4EF6 ${r} \u6302\u8F7D\u5931\u8D25:`,i)}}}getSortedPluginIds(){let e=Array.from(this.runtimes.keys()),t=new Set,r=[],n=new Set,i=o=>{if(t.has(o))return;if(n.has(o)){d.error(`\u5FAA\u73AF\u4F9D\u8D56\u68C0\u6D4B\u5230: ${o}`);return}n.add(o);let l=this.plugins.get(o);l?.metadata.dependencies&&l.metadata.dependencies.forEach(c=>{this.runtimes.has(c)&&i(c)}),n.delete(o),t.add(o),r.push(o)},a={system:100,functional:50,business:10};return[...e].sort((o,l)=>{let c=a[this.plugins.get(o)?.metadata.type||""]||0;return(a[this.plugins.get(l)?.metadata.type||""]||0)-c}).forEach(o=>i(o)),r}async loadPlugins(e,t){d.info("\u5F00\u59CB\u52A0\u8F7D\u63D2\u4EF6...");let r=Object.entries(t).map(async([a,s])=>{try{let o=await s(),l=e[a],c=this.instantiatePlugin(a,o,l);return c&&l&&m.set(c.id,l),c}catch(o){return d.error(`\u52A0\u8F7D\u672C\u5730\u63D2\u4EF6\u6A21\u5757 ${a} \u5931\u8D25:`,o),null}}),n=Object.entries(e).filter(([a,s])=>s.url&&!t[a]).map(async([a,s])=>{try{let o=await this.loadRemotePlugin(a,s.url,s);return o&&s&&m.set(o.id,s),o}catch(o){return d.error(`\u52A0\u8F7D\u5728\u7EBF\u63D2\u4EF6 ${a} \u5931\u8D25:`,o),null}});(await Promise.all([...r,...n])).forEach(a=>{a&&this.register(a,!1)}),this.notify(),d.info(`\u63D2\u4EF6\u52A0\u8F7D\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.plugins.size} \u4E2A\u63D2\u4EF6`)}async loadRemotePlugin(e,t,r){if(d.info(`\u6B63\u5728\u4ECE ${t} \u52A0\u8F7D\u8FDC\u7A0B\u63D2\u4EF6 ${e}...`),r?.format==="iife")return this.loadIIFEPlugin(e,t,r);try{let i=await new Function("specifier","return import(specifier)")(t);return this.instantiatePlugin(e,i,r)}catch{return d.warn(`ESM \u52A0\u8F7D\u5931\u8D25\uFF0C\u5C1D\u8BD5 IIFE \u52A0\u8F7D: ${e}`),this.loadIIFEPlugin(e,t,r)}}loadIIFEPlugin(e,t,r){return new Promise((n,i)=>{let a=document.createElement("script");a.src=t,a.onload=()=>{let s=e.replace(/[^a-zA-Z0-9]/g,"_"),o=window[s];o?n(this.instantiatePlugin(e,o,r)):i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u540E\u672A\u627E\u5230\u5168\u5C40\u53D8\u91CF ${s}`))},a.onerror=()=>i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: ${t}`)),document.head.appendChild(a)})}instantiatePlugin(e,t,r){let n=t.default;if(!n){let i=Object.keys(t).find(a=>a.endsWith("Plugin"));i&&(n=t[i])}if(!n&&typeof t=="object"&&t.id&&t.metadata&&(n=t),n){typeof n=="function"&&n.prototype&&d.warn(`\u63D2\u4EF6 ${e} \u4F7F\u7528\u4E86\u7C7B\u5B9A\u4E49\u6A21\u5F0F\u3002\u5EFA\u8BAE\u7EDF\u4E00\u4F7F\u7528 definePlugin() \u5DE5\u5382\u6A21\u5F0F\u4EE5\u6D88\u9664\u6B67\u4E49\u5E76\u7B80\u5316\u4EE3\u7801\u3002`);let a=typeof n=="function"?new n:n;if(!(e.includes("/")&&(e.includes(".ts")||e.includes(".tsx")))&&e&&a.metadata&&a.metadata.id!==e&&(a.metadata.id=e),!a.id&&a.metadata?.id)try{a.id=a.metadata.id}catch{}return r&&(a.defaultConfig={...a.defaultConfig,...r}),a}return d.warn(`\u6A21\u5757 ${e} \u672A\u5BFC\u51FA\u6709\u6548\u7684\u63D2\u4EF6\u5165\u53E3`),null}validatePlugin(e){return!(!e.id||!e.metadata)}handleBusinessPlugin(e){}handleFunctionalPlugin(e){}handleViewPlugin(e){}handleThemePlugin(e){}handleSystemPlugin(e){}},h=new V(new N);import{Fragment as ee,jsx as C}from"react/jsx-runtime";var wt=({slot:g,props:e={},className:t,style:r,renderItem:n,skeleton:i,fallback:a})=>{let[,s]=pe({});he(()=>h.subscribe(()=>{s({})}),[]);let o=h.getExtensions(g),l=h.getSystemConfig("title")?{title:h.getSystemConfig("title"),logo:h.getSystemConfig("logo"),version:h.getSystemConfig("version")}:void 0,c=X(()=>({...e,systemConfig:l}),[e,l]),u=X(()=>o.map((p,v)=>{let L=p.component,S=p.meta?.key||`${p.slot}-${p.order||0}-${v}`;return{key:S,extension:p,component:C(O,{pluginId:`extension-${S}`,children:C(L,{...c})},S)}}),[o,c]);return u.length===0?a?C(ee,{children:a}):i?C("div",{className:`plugin-slot plugin-slot-${g} plugin-slot-skeleton ${t||""}`,style:r,children:i}):null:u.length===1&&g==="root-layout"&&!t&&!r&&!n?C(ee,{children:u[0].component}):C("div",{className:`plugin-slot plugin-slot-${g} ${t||""}`,style:r,children:n?u.map((p,v)=>n(p,v)):u.map(p=>p.component)})};import{jsx as M,jsxs as me}from"react/jsx-runtime";var Et=({expanded:g=!1})=>me("div",{className:`flex items-center transition-all duration-300 relative
|
|
8
|
-
${g?"w-full":"w-12 justify-center"} px-3 h-11 rounded-xl`,children:[
|
|
7
|
+
`;return(0,eval)(t)}createFakeWindow(e){let t=new Map,r={};return Object.getOwnPropertyNames(e).forEach(n=>{let i=Object.getOwnPropertyDescriptor(e,n);i&&i.configurable}),{fakeWindow:r,propertiesWithGetter:t}}isConstructor(e){let t=e.prototype;return!!(t&&t.constructor===e&&Object.getOwnPropertyNames(t).length>0)}isNativeFunction(e){return e.toString().indexOf("[native code]")>-1}patchGlobalEffects(e){e.setTimeout=(t,r,...n)=>{let i=this.globalContext.setTimeout(t,r,...n);return this.effectPool.timeouts.add(i),i},e.clearTimeout=t=>{t&&(this.effectPool.timeouts.delete(t),this.globalContext.clearTimeout(t))},e.setInterval=(t,r,...n)=>{let i=this.globalContext.setInterval(t,r,...n);return this.effectPool.intervals.add(i),i},e.clearInterval=t=>{t&&(this.effectPool.intervals.delete(t),this.globalContext.clearInterval(t))},e.addEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t)||[];return i.push({listener:r,options:n}),this.effectPool.listeners.set(t,i),this.globalContext.addEventListener(t,r,n)},e.removeEventListener=(t,r,n)=>{let i=this.effectPool.listeners.get(t);if(i){let o=i.findIndex(a=>a.listener===r&&a.options===n);o!==-1&&i.splice(o,1)}return this.globalContext.removeEventListener(t,r,n)}}};var L=class{pluginId;storageManager;constructor(e,t){this.pluginId=e,this.storageManager=t}get storage(){return this.storageManager.getContextStorage(this.pluginId)}get logger(){return f(`Plugin:${this.pluginId}`)}};var S=f("PluginRuntime"),$=class{plugin;context;storageSandbox;windowSandbox;isLoaded=!1;isMounted=!1;error=null;constructor(e,t,r){this.plugin=e,this.storageSandbox=new L(e.id,r),this.windowSandbox=new I(e.id),this.context={pluginId:e.id,api:t.api,events:t.events,storage:this.storageSandbox.storage,logger:this.storageSandbox.logger,window:this.windowSandbox.proxy,getService:n=>C.get(n),registerService:(n,i)=>C.register(`${e.id}.${n}`,i)}}async load(){if(!this.isLoaded){S.debug(`\u6B63\u5728\u52A0\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.metadata.api&&this.context.api&&typeof this.context.api.register=="function"&&(this.context.api.register(this.plugin.metadata.api),S.debug(`\u5DF2\u4E3A\u63D2\u4EF6 ${this.plugin.id} \u81EA\u52A8\u6CE8\u518C API \u914D\u7F6E`)),this.plugin.onLoad&&await this.plugin.onLoad(this.context),this.isLoaded=!0,this.error=null,S.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u52A0\u8F7D\u3002`)}catch(e){this.error=e instanceof Error?e:new Error(String(e)),S.error(`\u63D2\u4EF6 ${this.plugin.id} \u52A0\u8F7D\u5931\u8D25:`,e)}}}async mount(){if(this.isLoaded||await this.load(),!this.isMounted){S.debug(`\u6B63\u5728\u6302\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.windowSandbox.active(),this.plugin.onMount&&this.plugin.onMount(this.context),this.isMounted=!0,this.error=null,S.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u6302\u8F7D\u3002`)}catch(e){this.error=e instanceof Error?e:new Error(String(e)),S.error(`\u63D2\u4EF6 ${this.plugin.id} \u6302\u8F7D\u5931\u8D25:`,e)}}}async unmount(){if(this.isMounted){S.debug(`\u6B63\u5728\u5378\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);try{this.plugin.onUnmount&&this.plugin.onUnmount(this.context)}catch(e){S.error(`\u63D2\u4EF6 ${this.plugin.id} \u5378\u8F7D\u65F6\u51FA\u9519:`,e)}finally{this.windowSandbox.inactive(),this.isMounted=!1,this.error=null,S.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u5378\u8F7D\u3002`)}}}async destroy(){await this.unmount(),this.isLoaded=!1,this.error=null}_setError(e){this.error=e}getError(){return this.error}get status(){return this.error?"error":this.isMounted?"mounted":this.isLoaded?"loaded":"initial"}};var w=class{constructor(e,t){this.underlyingStorage=e;this.prefix=t}getKey(e){return this.prefix?`${this.prefix}:${e}`:e}getOriginalKey(e){return this.prefix?e.startsWith(this.prefix+":")?e.slice(this.prefix.length+1):null:e}getItem(e){return this.underlyingStorage.getItem(this.getKey(e))}setItem(e,t){this.underlyingStorage.setItem(this.getKey(e),t)}removeItem(e){this.underlyingStorage.removeItem(this.getKey(e))}clear(){if(!this.prefix){this.underlyingStorage.clear();return}let e=[];for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e.push(r)}e.forEach(t=>this.underlyingStorage.removeItem(t))}get length(){let e=0;for(let t=0;t<this.underlyingStorage.length;t++){let r=this.underlyingStorage.key(t);r&&r.startsWith(this.prefix+":")&&e++}return e}key(e){let t=0;for(let r=0;r<this.underlyingStorage.length;r++){let n=this.underlyingStorage.key(r);if(n&&n.startsWith(this.prefix+":")){if(t===e)return this.getOriginalKey(n);t++}}return null}};var O=class{baseStorage;schemas=new Map;memoryCache=new Map;constructor(e){this.baseStorage=e}registerSchema(e,t){this.schemas.set(e,t)}validateKey(e,t,r="plugin"){let n=this.schemas.get(e);if(!n)return;let i=n.find(a=>a.key===t);if(!i){console.warn(`[Storage] Key "${t}" not defined in plugin "${e}" schema.`);return}let o=i.scope||"plugin";o!==r&&console.warn(`[Storage] Key "${t}" defined in scope "${o}" but accessed via "${r}".`)}getPluginStorage(e){return new w(this.baseStorage,`plugin:${e}`)}getSharedStorage(){return new w(this.baseStorage,"shared")}getSystemStorage(){return new w(this.baseStorage,"system")}getContextStorage(e){let t=this.getPluginStorage(e),r=this.getSharedStorage(),n=(i,o)=>{let a=o==="plugin"?`plugin:${e}:`:"shared:";return{get:s=>{this.validateKey(e,s,o);let l=`${a}${s}`;try{if(this.memoryCache.has(l))return this.memoryCache.get(l);let c=i.getItem(s);if(c!==null){let u;try{u=JSON.parse(c)}catch{u=c}return this.memoryCache.set(l,u),u}if(o==="plugin"){let u=m.get(e);if(u&&u[s]!==void 0)return u[s]}let d=this.schemas.get(e)?.find(u=>u.key===s);return d&&d.default!==void 0?d.default:null}catch(c){return console.warn(`[Storage] Failed to read key "${s}"`,c),null}},set:(s,l)=>{this.validateKey(e,s,o);let c=`${a}${s}`;try{this.memoryCache.set(c,l),i.setItem(s,JSON.stringify(l))}catch(d){console.warn(`[Storage] Failed to stringify key "${s}"`,d)}},remove:s=>{this.validateKey(e,s,o);let l=`${a}${s}`;this.memoryCache.delete(l),i.removeItem(s)}}};return{...n(t,"plugin"),shared:n(r,"shared")}}};var p=f("PluginManager"),B=class{eventBus=new k;storageManager;runtimes=new Map;plugins=new Map;routes=[];extensions=new Map;pluginStates={};listeners=new Set;slotListeners=new Map;memoizedExtensions=new Map;memoizedRoutes=null;sharedContext=null;utils={};constructor(e){this.storageManager=new O(e),this.loadStates(),this.subscribe(()=>{this.saveStates()})}loadStates(){try{let t=this.storageManager.getSystemStorage().getItem("plugin_states");t&&(this.pluginStates=JSON.parse(t),p.debug("\u4ECE\u7CFB\u7EDF\u5B58\u50A8\u4E2D\u52A0\u8F7D\u72B6\u6001:",this.pluginStates))}catch(e){p.error("\u52A0\u8F7D\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}saveStates(){try{this.storageManager.getSystemStorage().setItem("plugin_states",JSON.stringify(this.pluginStates)),p.debug("\u5DF2\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5230\u5B58\u50A8")}catch(e){p.error("\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:",e)}}subscribe(e,t){if(t){let r=String(t);return this.slotListeners.has(r)||this.slotListeners.set(r,new Set),this.slotListeners.get(r).add(e),()=>{this.slotListeners.get(r)?.delete(e)}}else return this.listeners.add(e),()=>{this.listeners.delete(e)}}getStorageManager(){return this.storageManager}notify(e){e?this.memoizedExtensions.delete(String(e)):(this.memoizedExtensions.clear(),this.memoizedRoutes=null),this.listeners.forEach(t=>t()),e?this.slotListeners.get(String(e))?.forEach(t=>t()):this.slotListeners.forEach(t=>t.forEach(r=>r()))}getPlugins(){let e={system:0,theme:1,renderer:2,functional:3,business:4,view:5};return Array.from(this.plugins.values()).sort((t,r)=>{let n=e[t.metadata.type]??99,i=e[r.metadata.type]??99;if(n!==i)return n-i;let o=this.pluginStates[t.id]||{order:0},a=this.pluginStates[r.id]||{order:0};return o.order-a.order})}getPluginState(e){return this.pluginStates[e]||{enabled:!0,order:0}}isPluginEnabled(e){let t=this.pluginStates[e];return t?t.enabled:!0}togglePlugin(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};if(this.pluginStates[e]={...r,enabled:t},t){if(this.sharedContext){let n=this.plugins.get(e);if(n)try{let i=new $(n,this.sharedContext,this.storageManager);this.runtimes.set(e,i),i.mount()}catch(i){p.error(`\u542F\u7528\u63D2\u4EF6 ${e} \u5931\u8D25:`,i)}}}else{let n=this.runtimes.get(e);n&&(n.unmount(),this.runtimes.delete(e))}this.notify()}setPluginOrder(e,t){let r=this.pluginStates[e]||{enabled:!0,order:0};this.pluginStates[e]={...r,order:t},this.notify()}getPluginRuntimeStatus(e){let t=this.runtimes.get(e);return t?t.status:"initial"}getPluginError(e){let t=this.runtimes.get(e);return t?t.getError():null}reportPluginError(e,t){let r=this.runtimes.get(e);r&&(r._setError?.(t),this.notify())}getUnifiedCapabilities(e){return this.plugins.get(e)?.metadata.capabilities||{}}updatePluginConfig(e,t,r){let n=m.get(e)||{};n[t]=r,m.set(e,n);try{this.storageManager.getContextStorage(e).set(t,r)}catch(i){p.warn("\u4FDD\u5B58\u914D\u7F6E\u5230\u5B58\u50A8\u5931\u8D25",i)}this.eventBus.emit("config:changed",{pluginId:e,key:t,value:r})}getPluginConfig(e,t){let r=m.get(e);return r?r[t]:void 0}getSystemConfig(e){let t=m.get("system");return t?t[e]:void 0}getService(e){return C.get(e)}getExtensions(e){let t=String(e);if(this.memoizedExtensions.has(t))return this.memoizedExtensions.get(t);let r=e,n=this.extensions.get(r)||[];n=n.filter(o=>{let a=o._pluginId;return!a||this.isPluginEnabled(a)});let i=n.sort((o,a)=>(o.order||0)-(a.order||0));return this.memoizedExtensions.set(t,i),i}getRoutes(){if(this.memoizedRoutes)return this.memoizedRoutes;let e=[];return this.getPlugins().forEach(t=>{if(this.isPluginEnabled(t.id)&&t.metadata.routes){let r=m.get(t.id)||{};t.metadata.routes.forEach(n=>{e.push({...n,meta:{...n.meta,pluginId:t.id,config:r}})})}}),this.memoizedRoutes=e,e}register(e,t=!0){if(!this.validatePlugin(e)){p.error(`\u63D2\u4EF6\u6CE8\u518C\u5931\u8D25: ${e?.id||"\u672A\u77E5"}`);return}if(this.plugins.has(e.id))return;let r=[...e.metadata.storage||[],...e.metadata.configuration?.map(s=>({key:s.key,type:s.type==="select"?"string":s.type,label:s.label,description:s.description,default:s.default,scope:"plugin"}))||[]];r.length>0&&this.storageManager.registerSchema(e.id,r),this.pluginStates[e.id]||(this.pluginStates[e.id]={enabled:!0,order:0});let n={},i={},o=this.storageManager.getPluginStorage(e.id);e.metadata.configuration&&e.metadata.configuration.forEach(s=>{s.default!==void 0&&(n[s.key]=s.default);try{let l=o.getItem(s.key);l!==null&&(i[s.key]=JSON.parse(l))}catch{}});let a={...n,...e.defaultConfig,...m.get(e.id)||{},...i};switch(m.set(e.id,a),e.metadata.type){case"business":this.handleBusinessPlugin(e);break;case"functional":this.handleFunctionalPlugin(e);break;case"view":this.handleViewPlugin(e);break;case"theme":this.handleThemePlugin(e);break;case"system":this.handleSystemPlugin(e);break;case"renderer":break;default:p.warn(`\u63D2\u4EF6 ${e.id} \u7C7B\u578B\u672A\u77E5: ${e.metadata.type}`);break}e.metadata.routes&&e.metadata.routes.length>0&&p.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u8DEF\u7531:`,e.metadata.routes),e.metadata.extensions&&e.metadata.extensions.length>0&&(e.metadata.extensions.forEach(s=>{let l=this.extensions.get(s.slot)||[];l.push({...s,_pluginId:e.id}),this.extensions.set(s.slot,l)}),p.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${e.id} \u6536\u96C6\u6269\u5C55\u70B9`)),this.plugins.set(e.id,e),p.info(`\u63D2\u4EF6 ${e.id} \u5DF2\u6CE8\u518C\u4E3A ${e.metadata.type}\u3002`),t&&this.notify()}async initPlugins(e={}){this.sharedContext={...e,events:this.eventBus},this.plugins.forEach(r=>{if(this.isPluginEnabled(r.id)&&!this.runtimes.has(r.id)){let n=new $(r,this.sharedContext,this.storageManager);this.runtimes.set(r.id,n)}});let t=this.getSortedPluginIds();for(let r of t){let n=this.runtimes.get(r);if(n)try{console.log(`[PluginManager] invoking onLoad for ${r}`),await n.load(),console.log(`[PluginManager] onLoad completed for ${r}`)}catch(i){p.error(`\u63D2\u4EF6 ${r} \u52A0\u8F7D\u5931\u8D25:`,i)}}for(let r of t){let n=this.runtimes.get(r);if(n)try{await n.mount()}catch(i){p.error(`\u63D2\u4EF6 ${r} \u6302\u8F7D\u5931\u8D25:`,i)}}}getSortedPluginIds(){let e=Array.from(this.runtimes.keys()),t=new Set,r=[],n=new Set,i=s=>{if(t.has(s))return;if(n.has(s)){p.error(`\u5FAA\u73AF\u4F9D\u8D56\u68C0\u6D4B\u5230: ${s}`);return}n.add(s);let l=this.plugins.get(s);l?.metadata.dependencies&&l.metadata.dependencies.forEach(c=>{this.runtimes.has(c)&&i(c)}),n.delete(s),t.add(s),r.push(s)},o={system:100,functional:50,business:10};return[...e].sort((s,l)=>{let c=o[this.plugins.get(s)?.metadata.type||""]||0;return(o[this.plugins.get(l)?.metadata.type||""]||0)-c}).forEach(s=>i(s)),r}async loadPlugins(e,t){p.info("\u5F00\u59CB\u52A0\u8F7D\u63D2\u4EF6...");let r=Object.entries(t).map(async([o,a])=>{try{let s=await a(),l=e[o],c=this.instantiatePlugin(o,s,l);return c&&l&&m.set(c.id,l),c}catch(s){return p.error(`\u52A0\u8F7D\u672C\u5730\u63D2\u4EF6\u6A21\u5757 ${o} \u5931\u8D25:`,s),null}}),n=Object.entries(e).filter(([o,a])=>a.url&&!t[o]).map(async([o,a])=>{try{let s=await this.loadRemotePlugin(o,a.url,a);return s&&a&&m.set(s.id,a),s}catch(s){return p.error(`\u52A0\u8F7D\u5728\u7EBF\u63D2\u4EF6 ${o} \u5931\u8D25:`,s),null}});(await Promise.all([...r,...n])).forEach(o=>{o&&this.register(o,!1)}),this.notify(),p.info(`\u63D2\u4EF6\u52A0\u8F7D\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.plugins.size} \u4E2A\u63D2\u4EF6`)}async loadRemotePlugin(e,t,r){if(p.info(`\u6B63\u5728\u4ECE ${t} \u52A0\u8F7D\u8FDC\u7A0B\u63D2\u4EF6 ${e}...`),r?.format==="iife")return this.loadIIFEPlugin(e,t,r);try{let i=await new Function("specifier","return import(specifier)")(t);return this.instantiatePlugin(e,i,r)}catch{return p.warn(`ESM \u52A0\u8F7D\u5931\u8D25\uFF0C\u5C1D\u8BD5 IIFE \u52A0\u8F7D: ${e}`),this.loadIIFEPlugin(e,t,r)}}loadIIFEPlugin(e,t,r){return new Promise((n,i)=>{let o=document.createElement("script");o.src=t,o.onload=()=>{let a=e.replace(/[^a-zA-Z0-9]/g,"_"),s=window[a];s?n(this.instantiatePlugin(e,s,r)):i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u540E\u672A\u627E\u5230\u5168\u5C40\u53D8\u91CF ${a}`))},o.onerror=()=>i(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${e} \u52A0\u8F7D\u5931\u8D25: ${t}`)),document.head.appendChild(o)})}instantiatePlugin(e,t,r){let n=t.default;if(!n){let i=Object.keys(t).find(o=>o.endsWith("Plugin"));i&&(n=t[i])}if(!n&&typeof t=="object"&&t.id&&t.metadata&&(n=t),n){typeof n=="function"&&n.prototype&&p.warn(`\u63D2\u4EF6 ${e} \u4F7F\u7528\u4E86\u7C7B\u5B9A\u4E49\u6A21\u5F0F\u3002\u5EFA\u8BAE\u7EDF\u4E00\u4F7F\u7528 definePlugin() \u5DE5\u5382\u6A21\u5F0F\u4EE5\u6D88\u9664\u6B67\u4E49\u5E76\u7B80\u5316\u4EE3\u7801\u3002`);let o=typeof n=="function"?new n:n;if(!(e.includes("/")&&(e.includes(".ts")||e.includes(".tsx")))&&e&&o.metadata&&o.metadata.id!==e&&(o.metadata.id=e),!o.id&&o.metadata?.id)try{o.id=o.metadata.id}catch{}return r&&(o.defaultConfig={...o.defaultConfig,...r}),o}return p.warn(`\u6A21\u5757 ${e} \u672A\u5BFC\u51FA\u6709\u6548\u7684\u63D2\u4EF6\u5165\u53E3`),null}validatePlugin(e){return!(!e.id||!e.metadata)}handleBusinessPlugin(e){}handleFunctionalPlugin(e){}handleViewPlugin(e){}handleThemePlugin(e){}handleSystemPlugin(e){}},h=new B(new A);import{jsx as ge}from"react/jsx-runtime";var ae=f("PluginErrorBoundary"),N=class extends oe{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){ae.error(`\u63D2\u4EF6 ${this.props.pluginId||"\u672A\u77E5"} \u6E32\u67D3\u53D1\u751F\u9519\u8BEF:`,e,t),this.props.pluginId&&(console.warn(`[PluginError] \u63D2\u4EF6 "${this.props.pluginId}" \u6E32\u67D3\u5931\u8D25\u3002\u60A8\u53EF\u4EE5\u5728\u63D2\u4EF6\u7BA1\u7406\u9762\u677F\u67E5\u770B\u8BE6\u7EC6\u4FE1\u606F\u3002`),h.reportPluginError(this.props.pluginId,e))}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:this.props.silent?null:ge("div",{className:"plugin-error-placeholder hidden","data-plugin-id":this.props.pluginId,"data-error":this.state.error?.message}):this.props.children}};import{useMemo as V,useState as le,useEffect as ce}from"react";import{Fragment as G,jsx as E}from"react/jsx-runtime";var vt=({slot:g,props:e={},className:t="",style:r,renderItem:n,skeleton:i,fallback:o})=>{let[,a]=le({});ce(()=>h.subscribe(()=>{a({})},g),[g]);let s=h.getExtensions(g),l=h.getSystemConfig("title")?{title:h.getSystemConfig("title"),logo:h.getSystemConfig("logo"),version:h.getSystemConfig("version")}:void 0,c=V(()=>({...e,systemConfig:l}),[e,l]),d=V(()=>s.map((u,v)=>{let y=u.component,b=u.meta?.key||`${u.slot}-${u.order||0}-${v}`;return{key:b,extension:u,component:E(N,{pluginId:u._pluginId,children:E(y,{...c})},b)}}),[s,c]);return d.length===0?o?E(G,{children:o}):i?E("div",{className:`plugin-slot plugin-slot-${g} plugin-slot-skeleton ${t||""}`,style:r,children:i}):null:d.length===1&&g==="root-layout"&&!t&&!r&&!n?E(G,{children:d[0].component}):E("div",{className:`plugin-slot plugin-slot-${g} ${t||""}`,style:r,children:n?d.map((u,v)=>n(u,v)):d.map(u=>u.component)})};import{jsx as T,jsxs as ue}from"react/jsx-runtime";var bt=({expanded:g=!1})=>ue("div",{className:`flex items-center transition-all duration-300 relative
|
|
8
|
+
${g?"w-full":"w-12 justify-center"} px-3 h-11 rounded-xl`,children:[T("div",{className:"w-6 h-6 bg-slate-200 dark:bg-white/10 rounded-lg shrink-0 animate-pulse"}),g&&T("div",{className:"ml-3 flex-1 h-4 bg-slate-200 dark:bg-white/10 rounded animate-pulse"})]}),wt=()=>T("div",{className:"h-4 w-16 bg-slate-200 dark:bg-white/10 rounded animate-pulse"}),Et=()=>T("div",{className:"w-10 h-10 rounded-full bg-slate-200 dark:bg-white/10 animate-pulse"}),Rt=({className:g})=>T("div",{className:`bg-slate-200 dark:bg-white/10 rounded animate-pulse ${g||"w-full h-full"}`});var D=f("AutoLoader"),de=[{pathSegment:"@chatbi-plugins",idPrefix:"@chatbi-v/plugin"},{pathSegment:"@chatbi-apps",idPrefix:"@chatbi-v/app"},{pathSegment:"packages/plugins",idPrefix:"@chatbi-v/plugin"},{pathSegment:"packages/apps",idPrefix:"@chatbi-v/app"}],Y=g=>{let{modules:e,rules:t=de}=g,r={},n=t.map(i=>{let o=i.pathSegment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{...i,regex:new RegExp(`${o}/([^/]+)/src/index`)}});for(let i in e)try{let o=null;for(let a of n){let s=i.match(a.regex);if(s&&s[1]){o=`${a.idPrefix}-${s[1]}`,D.info(`\u89E3\u6790\u8DEF\u5F84\u6210\u529F: ${i} -> ${o}`);break}}o?r[o]=e[i]:D.warn(`\u65E0\u6CD5\u4ECE\u8DEF\u5F84\u89E3\u6790\u63D2\u4EF6 ID: ${i}\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u7B26\u5408\u547D\u540D\u7EA6\u5B9A\u3002`)}catch(o){D.error(`\u89E3\u6790\u63D2\u4EF6\u8DEF\u5F84\u5931\u8D25: ${i}`,o)}return r};var J="000000";import{createContext as pe,useContext as fe}from"react";import{jsx as he}from"react/jsx-runtime";var Q=pe(null),Lt=({manager:g,children:e})=>he(Q.Provider,{value:g,children:e}),Ot=()=>{let g=fe(Q);if(!g)throw new Error("usePluginManager must be used within a PluginProvider");return g};import me from"axios";var j=class{client;constructor(e="/api",t=1e4){this.client=me.create({baseURL:e,timeout:t}),this.client.interceptors.response.use(r=>r,r=>Promise.reject(r))}async request(e){return this.client.request(e)}async stream(e,t,r){let{onMessage:n,onError:i,onFinish:o}=t;try{let a=await this.client.request({...e,headers:{"Cache-Control":"no-cache",Pragma:"no-cache",...e.headers},adapter:async u=>{let v=this.client.getUri(u),y=await fetch(v,{method:u.method?.toUpperCase(),headers:u.headers,body:u.data?typeof u.data=="string"?u.data:JSON.stringify(u.data):void 0,signal:u.signal});return{data:y,status:y.status,statusText:y.statusText,headers:y.headers,config:u}}}),s=a instanceof Response?a:a.data;if(t.onResponse&&await t.onResponse(a))return;if(!(s instanceof Response))throw new Error("\u6D41\u5F0F\u8BF7\u6C42\u5931\u8D25\uFF1A\u672A\u80FD\u83B7\u53D6\u5230\u539F\u59CB\u54CD\u5E94\u6D41\uFF0C\u8BF7\u68C0\u67E5 Axios \u54CD\u5E94\u62E6\u622A\u5668\u662F\u5426\u6B63\u786E\u5904\u7406\u4E86 Response \u5BF9\u8C61\u3002");if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);if(!s.body)throw new Error("\u54CD\u5E94\u4F53\u4E3A\u7A7A");let l=s.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:u,value:v}=await l.read();if(u)break;d+=c.decode(v,{stream:!0});let y=d.split(`
|
|
9
9
|
|
|
10
|
-
`);
|
|
10
|
+
`);d=y.pop()||"";for(let b of y)n&&n(b+`
|
|
11
11
|
|
|
12
|
-
`)}
|
|
12
|
+
`)}d&&n&&n(d),o&&o()}catch(a){i&&i(a)}}};var x=f("ApiEngine"),K=class{adapter;config={};interceptors=[];constructor(e){this.adapter=e||new j}registerInterceptor(e){this.interceptors.push(e)}unregisterInterceptor(e){this.interceptors=this.interceptors.filter(t=>t!==e)}useAdapter(e){this.adapter=e}register(e){x.info("\u6B63\u5728\u6CE8\u518C API \u914D\u7F6E:",Object.keys(e)),this.config={...this.config,...e}}getEndpoint(e,t){return this.config[e]?.[t]}async call(e,t,r,n={}){let i=this.getEndpoint(e,t);if(!i)return x.warn(`\u672A\u627E\u5230 API \u5B9A\u4E49: ${e}.${t} (\u5F53\u524D\u5DF2\u6CE8\u518C\u6A21\u5757: ${Object.keys(this.config).join(", ")})`),Promise.resolve(void 0);let o=await this.prepareRequestConfig(i,r,n),a;try{a=await this.adapter.request(o,i)}catch(c){if(c.response)a=c.response;else throw c}if(await this.applyResponseInterceptors(a,o)){x.info("\u8BF7\u6C42\u88AB\u62E6\u622A\u5668\u52AB\u6301:",e,t);return}this.checkHttpStatus(a);let l=this.extractResponseData(a);return this.handleBusinessError(l,i,e,t),l}async stream(e,t,r,n={}){let i=this.getEndpoint(e,t);if(!i){x.warn(`\u672A\u627E\u5230 API \u5B9A\u4E49: ${e}.${t}\uFF0C\u8DF3\u8FC7\u6D41\u5F0F\u8BF7\u6C42\u3002`);return}if(!this.adapter.stream){x.warn("\u5F53\u524D API \u9002\u914D\u5668\u4E0D\u652F\u6301\u6D41\u5F0F\u4F20\u8F93\u3002");return}let o=await this.prepareRequestConfig(i,r,n),a={onMessage:n.onMessage,onError:n.onError,onFinish:n.onFinish};try{await this.adapter.stream(o,{...a,onResponse:async s=>await this.applyResponseInterceptors(s,o)?(x.info("\u6D41\u5F0F\u8BF7\u6C42\u88AB\u62E6\u622A\u5668\u52AB\u6301:",e,t),o.signal instanceof AbortController&&o.signal.abort(),!0):(this.checkHttpStatus(s),!1)},i)}catch(s){if(a.onError)a.onError(s);else throw s}}async prepareRequestConfig(e,t,r){let n=e.url,i=r.params||{};n=n.replace(/:([a-zA-Z0-9_]+)/g,(s,l)=>i[l]!==void 0?String(i[l]):t&&typeof t=="object"&&t[l]!==void 0?String(t[l]):`:${l}`);let o=e.method,a={...r,url:n,method:o};return o==="GET"||o==="DELETE"?a.params=t:a.data=t,this.applyRequestInterceptors(a)}async applyRequestInterceptors(e){let t=e;for(let r of this.interceptors)r.interceptRequest&&(t=await r.interceptRequest(t));return t}async applyResponseInterceptors(e,t){if(this.interceptors.length===0)return!1;let r=this.createInterceptorContext(e,t);for(let n of this.interceptors)if(n.interceptResponse&&await n.interceptResponse(r))return!0;return!1}checkHttpStatus(e){if(e&&e.status&&(e.status<200||e.status>=300)){let t=this.extractResponseData(e);if(!this.isBaseResponse(t))throw new Error(`Request failed with status ${e.status}`)}}extractResponseData(e){return this.isAxiosResponse(e)?e.data:e}handleBusinessError(e,t,r,n){if(!this.isBaseResponse(e))return;let i=e,o=String(i.code);if(!(o===J||o==="200"||o==="0")&&(t.errorStrategy||"reject")==="reject")throw x.error(`API \u8BF7\u6C42\u4E1A\u52A1\u9519\u8BEF (${r}.${n}):`,i.message),new Error(i.message||`Request failed with code ${o}`)}isBaseResponse(e){return e&&typeof e=="object"&&"code"in e&&("message"in e||"data"in e)}isAxiosResponse(e){return e&&typeof e=="object"&&"data"in e&&"status"in e&&"headers"in e}createInterceptorContext(e,t){return e&&typeof e=="object"&&"status"in e&&"headers"in e?{response:e,status:e.status,headers:e.headers,data:e.data,config:t}:{response:e,status:200,headers:{},data:e,config:t}}},Wt=new K;function Z(g="last"){if(typeof window>"u")return new URLSearchParams;let{search:e,hash:t}=window.location,r=new URLSearchParams(e),n=new URLSearchParams(t.split("?")[1]||""),i=[];r.forEach((a,s)=>i.push([s,a,"search"])),n.forEach((a,s)=>i.push([s,a,"hash"]));let o=new Map;return g==="first"?i.forEach(([a,s])=>{o.has(a)||o.set(a,s)}):g==="last"?i.forEach(([a,s])=>o.set(a,s)):g==="search"?(i.forEach(([a,s,l])=>{l==="search"&&o.set(a,s)}),n.forEach((a,s)=>{o.has(s)||o.set(s,a)})):g==="hash"&&(i.forEach(([a,s,l])=>{l==="hash"&&o.set(a,s)}),r.forEach((a,s)=>{o.has(s)||o.set(s,a)})),new URLSearchParams(Array.from(o.entries()))}function Ht(g){if(typeof window>"u")return"";let{pathname:e,search:t,hash:r}=window.location,n=new URLSearchParams(t);g.forEach(u=>n.delete(u));let i=n.toString(),o=r.split("?"),a=o[0],s=o[1]||"",l=new URLSearchParams(s);g.forEach(u=>l.delete(u));let c=l.toString(),d=a+(c?"?"+c:"");return e+(i?"?"+i:"")+d}var ye=(g,e)=>{let t=JSON.parse(JSON.stringify(g));return Object.keys(e).forEach(r=>{t[r]&&(t[r]={...t[r],...e[r]})}),t};function Yt(){let g=typeof process<"u"&&process.env.VITE_USE_MOCK==="true"||typeof window<"u"&&window.VITE_USE_MOCK==="true";if(typeof window<"u"){let t=Z().get("mock");if(t==="true")return!0;if(t==="false")return!1}return g}function Jt(g,e={}){let t={},r=n=>(n.split("/").pop()||"").replace(/\.mock\.(ts|js|tsx|jsx|json)$/,"").replace(/\.(ts|js|tsx|jsx|json)$/,"");return Object.entries(g).forEach(([n,i])=>{if(n.includes(".mock."))return;let o=r(n);if(!o||!i.default)return;let a=i.default,s=Object.entries(e).find(([l])=>r(l)===o&&l.includes(".mock."));if(s){let l=s[1],c=l.default||l;c&&(a=ye(a,c))}t[o]=a}),t}import P from"dayjs";import Se from"dayjs/plugin/relativeTime";import"dayjs/locale/zh-cn";P.extend(Se);P.locale("zh-cn");var gr={formatDate(g){return P(g).format("YYYY-MM-DD")},formatTime(g){return P(g).format("HH:mm:ss")},formatDateTime(g){return P(g).format("YYYY-MM-DD HH:mm:ss")},now(){return P().valueOf()},fromNow(g){return P(g).fromNow()},dayjs:P};var cr="1.0.0";import{useCallback as X,useState as ve}from"react";function yr(g,e,t={}){let{defaultValue:r,scope:n="plugin"}=t,i=h.getStorageManager(),o=X(()=>{let c=i.getContextStorage(g);return n==="shared"?c.shared:c},[g,n,i]),[a,s]=ve(()=>{try{if(typeof window>"u")return r;let d=o().get(e);return d!==null?d:r}catch(c){return console.warn(`[useStorageState] Error reading key "${e}"`,c),r}}),l=X(c=>{try{let d=c instanceof Function?c(a):c;s(d),o().set(e,d)}catch(d){console.warn(`[useStorageState] Error setting key "${e}":`,d)}},[e,a,o]);return[a,l]}import{useEffect as Pe,useRef as xe,useState as ee}from"react";var F=f("PluginLoader"),wr=g=>{let[e,t]=ee(!1),[r,n]=ee(0),i=xe(!1);return Pe(()=>{let o=h.subscribe(()=>{F.debug("Plugin state changed, refreshing UI..."),n(s=>s+1)});return(async()=>{if(!(i.current||e)){i.current=!0;try{let{discoveryRules:s=[],modules:l={},registry:c={},pluginConfigs:d,sharedContext:u={},baseUrl:v=window.location.origin}=g;F.info("Starting to load plugins...");let b={...Object.keys(l).length>0?Y({modules:l,rules:s.length>0?s:void 0}):{},...c};if(g.systemConfig){let{configManager:te}=await import("./config-manager-LQITPSUA.mjs");te.set("system",g.systemConfig)}await h.loadPlugins(d,b),await h.initPlugins(u),t(!0),F.info("Plugins loaded successfully")}catch(s){F.error("Failed to load plugins:",s)}finally{i.current=!1}}})(),()=>{o()}},[]),{pluginsLoaded:e,pluginVersion:r}};export{K as ApiEngine,Le as ApiProvider,Et as AvatarSkeleton,j as AxiosAdapter,z as BasePlugin,Rt as BlockSkeleton,be as ConfigManager,k as DefaultEventBus,A as LocalStorageAdapter,W as LogLevel,M as Logger,we as PLUGIN_TYPES,N as PluginErrorBoundary,B as PluginManager,Lt as PluginProvider,$ as PluginRuntime,L as PluginSandbox,vt as PluginSlot,I as ProxySandbox,J as SUCCESS_CODE,w as ScopedStorageAdapter,q as ServiceRegistry,bt as SidebarIconSkeleton,Ee as Slot,wt as StatusBarItemSkeleton,O as StorageManager,Wt as apiEngine,Ht as cleanUrlParams,m as configManager,f as createLogger,gr as dateUtils,Re as definePlugin,Yt as isMockMode,$e as logger,Z as normalizeParams,h as pluginManager,Jt as resolveApiModules,Y as resolvePluginRegistry,C as serviceRegistry,Oe as useApi,wr as usePluginLoader,Ot as usePluginManager,yr as useStorageState,cr as version};
|
package/dist/ports/api-port.d.ts
CHANGED
|
@@ -6,98 +6,127 @@ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
|
6
6
|
* 错误处理策略
|
|
7
7
|
*/
|
|
8
8
|
export type ErrorStrategy = 'reject' | 'resolve' | 'silent';
|
|
9
|
+
/**
|
|
10
|
+
* API 接口端点配置
|
|
11
|
+
*/
|
|
9
12
|
export interface ApiEndpointConfig {
|
|
10
13
|
/** 接口路径 (支持 :param 语法) */
|
|
11
14
|
url: string;
|
|
12
15
|
/** 请求方法 */
|
|
13
16
|
method: HttpMethod;
|
|
14
|
-
/**
|
|
17
|
+
/** 接口描述 */
|
|
15
18
|
desc?: string;
|
|
16
|
-
/** Mock
|
|
19
|
+
/** Mock 响应数据结构定义 */
|
|
17
20
|
responseSchema?: any;
|
|
18
21
|
/** 错误处理策略 */
|
|
19
22
|
errorStrategy?: ErrorStrategy;
|
|
20
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* API 请求配置
|
|
26
|
+
*/
|
|
21
27
|
export interface ApiRequestConfig {
|
|
28
|
+
/** 请求 URL */
|
|
22
29
|
url: string;
|
|
30
|
+
/** 请求方法 */
|
|
23
31
|
method: HttpMethod;
|
|
32
|
+
/** 请求体数据 (POST/PUT 等) */
|
|
24
33
|
data?: any;
|
|
34
|
+
/** 查询参数 (GET 等) */
|
|
25
35
|
params?: any;
|
|
36
|
+
/** 请求头 */
|
|
26
37
|
headers?: any;
|
|
27
|
-
/**
|
|
38
|
+
/** 用于取消请求的信号对象 */
|
|
28
39
|
signal?: AbortSignal;
|
|
29
40
|
}
|
|
30
41
|
/**
|
|
31
|
-
*
|
|
42
|
+
* 流式响应回调函数接口
|
|
32
43
|
*/
|
|
33
44
|
export interface StreamCallbacks {
|
|
45
|
+
/** 收到消息片段时的回调 */
|
|
34
46
|
onMessage?: (data: any) => void;
|
|
47
|
+
/** 发生错误时的回调 */
|
|
35
48
|
onError?: (error: any) => void;
|
|
49
|
+
/** 请求完成时的回调 */
|
|
36
50
|
onFinish?: () => void;
|
|
51
|
+
/** 收到 HTTP 响应头部信息的回调,返回 true 表示劫持并中止流 */
|
|
52
|
+
onResponse?: (response: any) => Promise<boolean> | boolean;
|
|
37
53
|
}
|
|
38
54
|
/**
|
|
39
|
-
* API
|
|
40
|
-
* @description
|
|
55
|
+
* API 适配器端口接口
|
|
56
|
+
* @description 所有底层请求引擎(如 Fetch, Axios, Mock)都必须实现此接口,以确保内核对具体通信库的解耦。
|
|
41
57
|
*/
|
|
42
58
|
export interface ApiAdapter {
|
|
59
|
+
/**
|
|
60
|
+
* 发起普通 HTTP 请求
|
|
61
|
+
* @param config - 请求配置
|
|
62
|
+
* @param endpointConfig - 接口端点定义的元数据配置
|
|
63
|
+
* @returns 响应数据的 Promise
|
|
64
|
+
*/
|
|
43
65
|
request<T = any>(config: ApiRequestConfig, endpointConfig?: ApiEndpointConfig): Promise<T>;
|
|
44
66
|
/**
|
|
45
|
-
* 发起流式请求
|
|
67
|
+
* 发起流式请求 (SSE 或 Chunked Transfer)
|
|
68
|
+
* @param config - 请求配置
|
|
69
|
+
* @param callbacks - 流式处理的回调函数集合
|
|
70
|
+
* @param endpointConfig - 接口端点定义的元数据配置
|
|
46
71
|
*/
|
|
47
72
|
stream?(config: ApiRequestConfig, callbacks: StreamCallbacks, endpointConfig?: ApiEndpointConfig): Promise<void>;
|
|
48
73
|
}
|
|
49
74
|
/**
|
|
50
|
-
* API 配置集合 (
|
|
75
|
+
* API 配置集合 (按模块和动作分组)
|
|
51
76
|
*/
|
|
52
77
|
export interface ApiConfig {
|
|
78
|
+
/** 模块名称 */
|
|
53
79
|
[module: string]: {
|
|
80
|
+
/** 动作/接口名称 */
|
|
54
81
|
[action: string]: ApiEndpointConfig;
|
|
55
82
|
};
|
|
56
83
|
}
|
|
57
84
|
/**
|
|
58
|
-
*
|
|
85
|
+
* 业务侧发起请求时的选项
|
|
59
86
|
*/
|
|
60
87
|
export interface RequestOptions extends Partial<ApiRequestConfig> {
|
|
61
|
-
/**
|
|
88
|
+
/** 是否跳过全局错误处理逻辑 */
|
|
62
89
|
skipErrorHandler?: boolean;
|
|
63
|
-
/**
|
|
90
|
+
/** 路径参数集合 (将替换 url 中的 :param 占位符) */
|
|
64
91
|
params?: any;
|
|
65
|
-
/**
|
|
92
|
+
/** 流式响应:收到数据片段的回调 */
|
|
66
93
|
onMessage?: (data: any) => void;
|
|
94
|
+
/** 流式响应:发生错误的回调 */
|
|
67
95
|
onError?: (error: any) => void;
|
|
96
|
+
/** 流式响应:正常结束的回调 */
|
|
68
97
|
onFinish?: () => void;
|
|
69
|
-
/**
|
|
98
|
+
/** 允许透传其他底层适配器所需的属性 (例如 axios 的特定配置) */
|
|
70
99
|
[key: string]: any;
|
|
71
100
|
}
|
|
72
101
|
/**
|
|
73
|
-
* API
|
|
102
|
+
* API 响应拦截上下文对象
|
|
74
103
|
*/
|
|
75
104
|
export interface ApiResponseContext {
|
|
76
|
-
/**
|
|
105
|
+
/** 原始响应对象 (例如 AxiosResponse 或 Fetch Response) */
|
|
77
106
|
response: any;
|
|
78
|
-
/** 响应状态码 */
|
|
107
|
+
/** HTTP 响应状态码 */
|
|
79
108
|
status: number;
|
|
80
|
-
/**
|
|
109
|
+
/** 响应头集合 */
|
|
81
110
|
headers: Record<string, string>;
|
|
82
|
-
/**
|
|
111
|
+
/** 解析后的业务数据体 */
|
|
83
112
|
data: any;
|
|
84
|
-
/**
|
|
113
|
+
/** 对应的原始请求配置 */
|
|
85
114
|
config: ApiRequestConfig;
|
|
86
115
|
}
|
|
87
116
|
/**
|
|
88
|
-
* API
|
|
117
|
+
* API 拦截器定义
|
|
89
118
|
*/
|
|
90
119
|
export interface ApiInterceptor {
|
|
91
120
|
/**
|
|
92
|
-
*
|
|
93
|
-
* @param config
|
|
94
|
-
* @returns
|
|
121
|
+
* 请求发送前的拦截逻辑
|
|
122
|
+
* @param config - 原始请求配置
|
|
123
|
+
* @returns 修改后的请求配置,或其 Promise
|
|
95
124
|
*/
|
|
96
125
|
interceptRequest?: (config: ApiRequestConfig) => ApiRequestConfig | Promise<ApiRequestConfig>;
|
|
97
126
|
/**
|
|
98
|
-
*
|
|
99
|
-
* @param context
|
|
100
|
-
* @returns 如果返回 true
|
|
127
|
+
* 响应接收后的拦截逻辑
|
|
128
|
+
* @param context - 响应上下文信息
|
|
129
|
+
* @returns 如果返回 true,表示该拦截器已接管并处理了响应,后续拦截器及业务回调将不再触发
|
|
101
130
|
*/
|
|
102
131
|
interceptResponse?: (context: ApiResponseContext) => boolean | Promise<boolean>;
|
|
103
132
|
}
|
|
@@ -1,30 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 事件总线端口接口
|
|
3
|
+
* @description 定义应用内部事件通信的标准契约,支持发布订阅模式。
|
|
3
4
|
*/
|
|
4
5
|
export interface EventBusPort {
|
|
5
6
|
/**
|
|
6
7
|
* 订阅事件
|
|
7
|
-
* @param event 事件名称
|
|
8
|
-
* @param callback
|
|
9
|
-
* @returns
|
|
8
|
+
* @param event - 事件名称
|
|
9
|
+
* @param callback - 事件触发时的回调函数
|
|
10
|
+
* @returns 取消订阅的函数
|
|
10
11
|
*/
|
|
11
12
|
on(event: string, callback: (...args: any[]) => any): () => void;
|
|
12
13
|
/**
|
|
13
|
-
*
|
|
14
|
-
* @param event 事件名称
|
|
15
|
-
* @param callback
|
|
14
|
+
* 取消订阅事件
|
|
15
|
+
* @param event - 事件名称
|
|
16
|
+
* @param callback - 之前注册的回调函数
|
|
16
17
|
*/
|
|
17
18
|
off(event: string, callback: (...args: any[]) => any): void;
|
|
18
19
|
/**
|
|
19
|
-
* 触发事件
|
|
20
|
-
* @param event 事件名称
|
|
21
|
-
* @param args
|
|
20
|
+
* 触发事件 (发布)
|
|
21
|
+
* @param event - 事件名称
|
|
22
|
+
* @param args - 传递给回调函数的参数列表
|
|
22
23
|
*/
|
|
23
24
|
emit(event: string, ...args: any[]): void;
|
|
24
25
|
/**
|
|
25
26
|
* 订阅一次性事件
|
|
26
|
-
* @
|
|
27
|
-
* @param
|
|
27
|
+
* @description 事件触发一次后会自动取消订阅
|
|
28
|
+
* @param event - 事件名称
|
|
29
|
+
* @param callback - 事件触发时的回调函数
|
|
28
30
|
*/
|
|
29
31
|
once(event: string, callback: (...args: any[]) => any): void;
|
|
30
32
|
}
|