@chatbi-v/core 2.1.0 → 2.1.2

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.
Files changed (46) hide show
  1. package/dist/chunk-QET56C3T.mjs +51 -0
  2. package/dist/chunk-QET56C3T.mjs.map +1 -0
  3. package/dist/config-manager-3TKURRUT.mjs +9 -0
  4. package/dist/config-manager-3TKURRUT.mjs.map +1 -0
  5. package/dist/index.d.mts +1748 -0
  6. package/dist/index.d.ts +1745 -27
  7. package/dist/index.js +2833 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/index.mjs +2685 -7
  10. package/dist/index.mjs.map +1 -0
  11. package/package.json +3 -3
  12. package/dist/adapters/local-storage-adapter.d.ts +0 -61
  13. package/dist/adapters/scoped-storage-adapter.d.ts +0 -61
  14. package/dist/api/adapters/axios-adapter.d.ts +0 -10
  15. package/dist/api/engine.d.ts +0 -87
  16. package/dist/api/index.d.ts +0 -6
  17. package/dist/api/utils.d.ts +0 -14
  18. package/dist/api-context.d.ts +0 -8
  19. package/dist/application/service-registry.d.ts +0 -57
  20. package/dist/chunk-O74KYN5N.mjs +0 -1
  21. package/dist/components/PluginErrorBoundary.d.ts +0 -44
  22. package/dist/components/PluginSlot.d.ts +0 -35
  23. package/dist/components/SlotSkeletons.d.ts +0 -27
  24. package/dist/config-manager-LQITPSUA.mjs +0 -1
  25. package/dist/config-manager.d.ts +0 -34
  26. package/dist/domain/auto-loader.d.ts +0 -36
  27. package/dist/domain/models.d.ts +0 -42
  28. package/dist/domain/plugin-manager.d.ts +0 -215
  29. package/dist/domain/plugin-runtime.d.ts +0 -70
  30. package/dist/domain/plugin-sandbox.d.ts +0 -40
  31. package/dist/domain/storage-manager.d.ts +0 -74
  32. package/dist/event-bus.d.ts +0 -38
  33. package/dist/hooks/use-plugin-loader.d.ts +0 -35
  34. package/dist/hooks/use-storage-state.d.ts +0 -15
  35. package/dist/index.cjs +0 -12
  36. package/dist/plugin-context.d.ts +0 -8
  37. package/dist/ports/api-port.d.ts +0 -132
  38. package/dist/ports/event-bus-port.d.ts +0 -32
  39. package/dist/ports/plugin-port.d.ts +0 -308
  40. package/dist/ports/storage-port.d.ts +0 -49
  41. package/dist/sandbox/proxy-sandbox.d.ts +0 -45
  42. package/dist/sandbox/style-isolation.d.ts +0 -13
  43. package/dist/utils/date.d.ts +0 -32
  44. package/dist/utils/index.d.ts +0 -4
  45. package/dist/utils/logger.d.ts +0 -79
  46. package/dist/utils/url.d.ts +0 -16
@@ -1,70 +0,0 @@
1
- /**
2
- * @file plugin-runtime.ts
3
- * @description 插件运行时,封装单个插件的生命周期(load/mount/unmount)、沙箱环境和隔离上下文
4
- * @author ChatBI Team
5
- */
6
- import { Plugin, PluginContext } from '../ports/plugin-port';
7
- import { StorageManager } from './storage-manager';
8
- /**
9
- * 插件运行时类
10
- * @description 为单个插件提供独立的运行环境,负责管理其生命周期、初始化沙箱环境并组装上下文对象。
11
- */
12
- export declare class PluginRuntime {
13
- /** 插件定义对象 */
14
- plugin: Plugin;
15
- /** 传递给插件的上下文对象 */
16
- context: PluginContext;
17
- /** 存储沙箱隔离设施 */
18
- private storageSandbox;
19
- /** Window/全局对象沙箱隔离设施 */
20
- private windowSandbox;
21
- /** 是否已完成加载阶段 */
22
- private isLoaded;
23
- /** 是否已完成挂载阶段 */
24
- private isMounted;
25
- /** 运行时捕获的错误信息 */
26
- private error;
27
- /**
28
- * 构造函数
29
- * @param plugin - 插件定义对象
30
- * @param sharedContext - 来自内核的共享上下文资源 (如 API 引擎、事件总线)
31
- * @param storageManager - 全局存储管理器
32
- */
33
- constructor(plugin: Plugin, sharedContext: Record<string, any>, storageManager: StorageManager);
34
- /**
35
- * 执行插件的加载逻辑 (onLoad)
36
- * @description 此阶段会自动注册插件声明的 API 配置,并调用插件的 onLoad 钩子。
37
- * 用于执行非 UI 的初始化逻辑,如注册服务、拦截器等。
38
- */
39
- load(): Promise<void>;
40
- /**
41
- * 执行插件的挂载逻辑 (onMount)
42
- * @description 此阶段会激活 Window 沙箱并调用插件的 onMount 钩子。
43
- * 此时插件的 UI 组件(如有)即将或已经进入 DOM。
44
- */
45
- mount(): Promise<void>;
46
- /**
47
- * 执行插件的卸载逻辑 (onUnmount)
48
- * @description 调用插件的 onUnmount 钩子并停用沙箱。
49
- */
50
- unmount(): Promise<void>;
51
- /**
52
- * 彻底销毁插件实例
53
- * @description 卸载插件并重置加载状态。
54
- */
55
- destroy(): Promise<void>;
56
- /**
57
- * 设置运行时错误 (内部使用)
58
- * @internal
59
- */
60
- _setError(error: Error | null): void;
61
- /**
62
- * 获取插件运行时错误
63
- */
64
- getError(): Error | null;
65
- /**
66
- * 获取插件当前运行状态
67
- * @returns 'error' | 'mounted' | 'loaded' | 'initial'
68
- */
69
- get status(): "error" | "mounted" | "loaded" | "initial";
70
- }
@@ -1,40 +0,0 @@
1
- import { StorageManager } from './storage-manager';
2
- /**
3
- * 插件隔离沙箱
4
- * @description 核心领域服务,为每个插件实例创建独立的运行上下文。
5
- * 它是插件与系统核心之间的“中间层”,确保插件只能访问其权限范围内的资源。
6
- * 主要职责:
7
- * 1. 存储隔离:确保插件只能读写属于自己的 LocalStorage 命名空间。
8
- * 2. 日志隔离:为插件提供带有自身 ID 前缀的日志输出,方便调试。
9
- */
10
- export declare class PluginSandbox {
11
- /** 关联的插件唯一标识 */
12
- private pluginId;
13
- /** 系统全局存储管理器 */
14
- private storageManager;
15
- /**
16
- * 构造插件沙箱
17
- * @param pluginId - 插件 ID
18
- * @param storageManager - 系统存储管理器实例
19
- */
20
- constructor(pluginId: string, storageManager: StorageManager);
21
- /**
22
- * 获取隔离的存储接口
23
- * @description 返回一个受限的 StoragePort,所有操作都会自动带上插件 ID 前缀。
24
- */
25
- get storage(): {
26
- shared: {
27
- get: <T = any>(key: string) => T | null;
28
- set: <T = any>(key: string, value: T) => void;
29
- remove: (key: string) => void;
30
- };
31
- get: <T = any>(key: string) => T | null;
32
- set: <T = any>(key: string, value: T) => void;
33
- remove: (key: string) => void;
34
- };
35
- /**
36
- * 获取隔离的日志接口
37
- * @description 返回一个带插件 ID 前缀的 Logger 实例。
38
- */
39
- get logger(): import("..").Logger;
40
- }
@@ -1,74 +0,0 @@
1
- import { StorageItemSchema } from '../ports/plugin-port';
2
- import { StoragePort } from '../ports/storage-port';
3
- /**
4
- * 核心领域服务:存储管理器
5
- * @description 统一管理应用内所有的持久化存储资源。
6
- * 核心功能:
7
- * 1. 作用域隔离:通过前缀划分 `plugin`、`shared` 和 `system` 三个层级的存储空间。
8
- * 2. Schema 校验:支持注册存储描述,规范数据存取,避免键名冲突。
9
- * 3. 默认值与配置回退:支持从 Schema 默认值或 ConfigManager 中回退取值。
10
- */
11
- export declare class StorageManager {
12
- /** 底层物理存储驱动 */
13
- private baseStorage;
14
- /** 插件 ID 与存储描述定义的映射关系 */
15
- private schemas;
16
- /** 内存缓存,减少 JSON 序列化和物理 IO 开销 */
17
- private memoryCache;
18
- /**
19
- * 初始化存储管理器
20
- * @param baseStorage - 符合 StoragePort 接口的物理存储驱动(如 LocalStorageAdapter)
21
- */
22
- constructor(baseStorage: StoragePort);
23
- /**
24
- * 注册插件的存储 Schema
25
- * @param pluginId - 插件 ID
26
- * @param schema - 存储项定义列表
27
- */
28
- registerSchema(pluginId: string, schema: StorageItemSchema[]): void;
29
- /**
30
- * 内部校验方法:检查键名是否在 Schema 中声明
31
- * @param pluginId - 插件 ID
32
- * @param key - 待校验的键名
33
- * @param scope - 目标作用域
34
- */
35
- private validateKey;
36
- /**
37
- * 获取插件私有存储适配器
38
- * @param pluginId - 插件 ID
39
- * @returns 自动添加 `plugin:{id}:` 前缀的存储接口
40
- */
41
- getPluginStorage(pluginId: string): StoragePort;
42
- /**
43
- * 获取全局共享存储适配器
44
- * @returns 自动添加 `shared:` 前缀的存储接口
45
- */
46
- getSharedStorage(): StoragePort;
47
- /**
48
- * 获取系统内部存储适配器
49
- * @returns 自动添加 `system:` 前缀的存储接口
50
- */
51
- getSystemStorage(): StoragePort;
52
- /**
53
- * 创建插件沙箱使用的复合存储对象
54
- * @description 返回的对象封装了对私有存储和共享存储的操作。
55
- * 特性:
56
- * - 内存级 LRU 缓存:极大提升高频读写性能。
57
- * - 自动序列化/反序列化 JSON。
58
- * - 自动校验 Schema。
59
- * - 取值回退逻辑:持久化存储 -> ConfigManager -> Schema 默认值。
60
- *
61
- * @param pluginId - 插件 ID
62
- * @returns 包含 get/set/remove 及 shared 子对象的复合接口
63
- */
64
- getContextStorage(pluginId: string): {
65
- shared: {
66
- get: <T = any>(key: string) => T | null;
67
- set: <T = any>(key: string, value: T) => void;
68
- remove: (key: string) => void;
69
- };
70
- get: <T = any>(key: string) => T | null;
71
- set: <T = any>(key: string, value: T) => void;
72
- remove: (key: string) => void;
73
- };
74
- }
@@ -1,38 +0,0 @@
1
- export type EventCallback = (...args: any[]) => any;
2
- /**
3
- * 事件总线接口
4
- */
5
- export interface EventBus {
6
- /**
7
- * 订阅事件
8
- * @param event 事件名称
9
- * @param callback 回调函数
10
- * @returns 取消订阅函数
11
- */
12
- on(event: string, callback: EventCallback): () => void;
13
- /**
14
- * 取消订阅
15
- * @param event 事件名称
16
- * @param callback 回调函数
17
- */
18
- off(event: string, callback: EventCallback): void;
19
- /**
20
- * 触发事件
21
- * @param event 事件名称
22
- * @param args 事件参数
23
- */
24
- emit(event: string, ...args: any[]): void;
25
- /**
26
- * 订阅一次性事件
27
- * @param event 事件名称
28
- * @param callback 回调函数
29
- */
30
- once(event: string, callback: EventCallback): void;
31
- }
32
- export declare class DefaultEventBus implements EventBus {
33
- private listeners;
34
- on(event: string, callback: EventCallback): () => void;
35
- off(event: string, callback: EventCallback): void;
36
- emit(event: string, ...args: any[]): void;
37
- once(event: string, callback: EventCallback): void;
38
- }
@@ -1,35 +0,0 @@
1
- /** 插件加载 Hook 的配置选项 */
2
- export interface PluginLoaderOptions {
3
- /** 插件发现规则,定义如何从模块列表中识别插件 */
4
- discoveryRules?: any[];
5
- /** 插件模块映射,通常由 Vite 的 `import.meta.glob` 生成,键为路径,值为加载函数 */
6
- modules?: Record<string, () => Promise<any>>;
7
- /** 预注册的插件注册表,用于手动指定插件加载逻辑,优先级高于自动发现 */
8
- registry?: Record<string, () => Promise<any>>;
9
- /** 插件的业务配置映射,键为插件 ID */
10
- pluginConfigs: Record<string, any>;
11
- /** 初始化的共享上下文服务,将注入到每个插件的 onLoad 中 */
12
- sharedContext?: Record<string, any>;
13
- /** 系统级全局配置,如标题、版本号、Logo 等 */
14
- systemConfig?: Record<string, any>;
15
- /** 资源发现的基础 URL,默认为当前 window.location.origin */
16
- baseUrl?: string;
17
- }
18
- /**
19
- * 核心 Hook:通用插件加载器
20
- * @description 负责应用启动时的插件全生命周期管理:
21
- * 1. 自动发现:解析 modules 并根据规则识别插件。
22
- * 2. 注册:将插件信息录入 PluginManager。
23
- * 3. 加载:调用插件的加载逻辑 (onLoad)。
24
- * 4. 初始化:调用插件的挂载逻辑 (onMount)。
25
- * 5. 响应式更新:订阅插件状态变更并触发 UI 刷新。
26
- *
27
- * @param options - 加载配置项
28
- * @returns { pluginsLoaded: boolean, pluginVersion: number }
29
- * - pluginsLoaded: 插件是否已全部完成初始化
30
- * - pluginVersion: 插件状态版本号,用于强制触发依赖插件状态的组件重渲染
31
- */
32
- export declare const usePluginLoader: (options: PluginLoaderOptions) => {
33
- pluginsLoaded: boolean;
34
- pluginVersion: number;
35
- };
@@ -1,15 +0,0 @@
1
- /**
2
- * Hook options
3
- */
4
- export interface UseStorageStateOptions<T> {
5
- defaultValue?: T;
6
- scope?: 'plugin' | 'shared';
7
- }
8
- /**
9
- * Unified Storage State Hook
10
- * @description Provides a persistent state hook that integrates with the StorageManager and Schema Registry.
11
- * @param pluginId The plugin ID defining the key
12
- * @param key The storage key (must be registered in schema)
13
- * @param options Options including default value and scope
14
- */
15
- export declare function useStorageState<T>(pluginId: string, key: string, options?: UseStorageStateOptions<T>): [T, (value: T | ((val: T) => T)) => void];
package/dist/index.cjs DELETED
@@ -1,12 +0,0 @@
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
- ;(function(window, self, globalThis){
3
- with(window) {
4
- ${e}
5
- }
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 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
-
10
- `);d=y.pop()||"";for(let $ of y)n&&n($+`
11
-
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});
@@ -1,8 +0,0 @@
1
- import React from 'react';
2
- import { PluginManager } from './domain/plugin-manager';
3
- export interface PluginProviderProps {
4
- manager: PluginManager;
5
- children: React.ReactNode;
6
- }
7
- export declare const PluginProvider: React.FC<PluginProviderProps>;
8
- export declare const usePluginManager: () => PluginManager;
@@ -1,132 +0,0 @@
1
- /**
2
- * HTTP 请求方法
3
- */
4
- export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
5
- /**
6
- * 错误处理策略
7
- */
8
- export type ErrorStrategy = 'reject' | 'resolve' | 'silent';
9
- /**
10
- * API 接口端点配置
11
- */
12
- export interface ApiEndpointConfig {
13
- /** 接口路径 (支持 :param 语法) */
14
- url: string;
15
- /** 请求方法 */
16
- method: HttpMethod;
17
- /** 接口描述 */
18
- desc?: string;
19
- /** Mock 响应数据结构定义 */
20
- responseSchema?: any;
21
- /** 错误处理策略 */
22
- errorStrategy?: ErrorStrategy;
23
- }
24
- /**
25
- * API 请求配置
26
- */
27
- export interface ApiRequestConfig {
28
- /** 请求 URL */
29
- url: string;
30
- /** 请求方法 */
31
- method: HttpMethod;
32
- /** 请求体数据 (POST/PUT 等) */
33
- data?: any;
34
- /** 查询参数 (GET 等) */
35
- params?: any;
36
- /** 请求头 */
37
- headers?: any;
38
- /** 用于取消请求的信号对象 */
39
- signal?: AbortSignal;
40
- }
41
- /**
42
- * 流式响应回调函数接口
43
- */
44
- export interface StreamCallbacks {
45
- /** 收到消息片段时的回调 */
46
- onMessage?: (data: any) => void;
47
- /** 发生错误时的回调 */
48
- onError?: (error: any) => void;
49
- /** 请求完成时的回调 */
50
- onFinish?: () => void;
51
- /** 收到 HTTP 响应头部信息的回调,返回 true 表示劫持并中止流 */
52
- onResponse?: (response: any) => Promise<boolean> | boolean;
53
- }
54
- /**
55
- * API 适配器端口接口
56
- * @description 所有底层请求引擎(如 Fetch, Axios, Mock)都必须实现此接口,以确保内核对具体通信库的解耦。
57
- */
58
- export interface ApiAdapter {
59
- /**
60
- * 发起普通 HTTP 请求
61
- * @param config - 请求配置
62
- * @param endpointConfig - 接口端点定义的元数据配置
63
- * @returns 响应数据的 Promise
64
- */
65
- request<T = any>(config: ApiRequestConfig, endpointConfig?: ApiEndpointConfig): Promise<T>;
66
- /**
67
- * 发起流式请求 (SSE 或 Chunked Transfer)
68
- * @param config - 请求配置
69
- * @param callbacks - 流式处理的回调函数集合
70
- * @param endpointConfig - 接口端点定义的元数据配置
71
- */
72
- stream?(config: ApiRequestConfig, callbacks: StreamCallbacks, endpointConfig?: ApiEndpointConfig): Promise<void>;
73
- }
74
- /**
75
- * API 配置集合 (按模块和动作分组)
76
- */
77
- export interface ApiConfig {
78
- /** 模块名称 */
79
- [module: string]: {
80
- /** 动作/接口名称 */
81
- [action: string]: ApiEndpointConfig;
82
- };
83
- }
84
- /**
85
- * 业务侧发起请求时的选项
86
- */
87
- export interface RequestOptions extends Partial<ApiRequestConfig> {
88
- /** 是否跳过全局错误处理逻辑 */
89
- skipErrorHandler?: boolean;
90
- /** 路径参数集合 (将替换 url 中的 :param 占位符) */
91
- params?: any;
92
- /** 流式响应:收到数据片段的回调 */
93
- onMessage?: (data: any) => void;
94
- /** 流式响应:发生错误的回调 */
95
- onError?: (error: any) => void;
96
- /** 流式响应:正常结束的回调 */
97
- onFinish?: () => void;
98
- /** 允许透传其他底层适配器所需的属性 (例如 axios 的特定配置) */
99
- [key: string]: any;
100
- }
101
- /**
102
- * API 响应拦截上下文对象
103
- */
104
- export interface ApiResponseContext {
105
- /** 原始响应对象 (例如 AxiosResponse 或 Fetch Response) */
106
- response: any;
107
- /** HTTP 响应状态码 */
108
- status: number;
109
- /** 响应头集合 */
110
- headers: Record<string, string>;
111
- /** 解析后的业务数据体 */
112
- data: any;
113
- /** 对应的原始请求配置 */
114
- config: ApiRequestConfig;
115
- }
116
- /**
117
- * API 拦截器定义
118
- */
119
- export interface ApiInterceptor {
120
- /**
121
- * 请求发送前的拦截逻辑
122
- * @param config - 原始请求配置
123
- * @returns 修改后的请求配置,或其 Promise
124
- */
125
- interceptRequest?: (config: ApiRequestConfig) => ApiRequestConfig | Promise<ApiRequestConfig>;
126
- /**
127
- * 响应接收后的拦截逻辑
128
- * @param context - 响应上下文信息
129
- * @returns 如果返回 true,表示该拦截器已接管并处理了响应,后续拦截器及业务回调将不再触发
130
- */
131
- interceptResponse?: (context: ApiResponseContext) => boolean | Promise<boolean>;
132
- }
@@ -1,32 +0,0 @@
1
- /**
2
- * 事件总线端口接口
3
- * @description 定义应用内部事件通信的标准契约,支持发布订阅模式。
4
- */
5
- export interface EventBusPort {
6
- /**
7
- * 订阅事件
8
- * @param event - 事件名称
9
- * @param callback - 事件触发时的回调函数
10
- * @returns 取消订阅的函数
11
- */
12
- on(event: string, callback: (...args: any[]) => any): () => void;
13
- /**
14
- * 取消订阅事件
15
- * @param event - 事件名称
16
- * @param callback - 之前注册的回调函数
17
- */
18
- off(event: string, callback: (...args: any[]) => any): void;
19
- /**
20
- * 触发事件 (发布)
21
- * @param event - 事件名称
22
- * @param args - 传递给回调函数的参数列表
23
- */
24
- emit(event: string, ...args: any[]): void;
25
- /**
26
- * 订阅一次性事件
27
- * @description 事件触发一次后会自动取消订阅
28
- * @param event - 事件名称
29
- * @param callback - 事件触发时的回调函数
30
- */
31
- once(event: string, callback: (...args: any[]) => any): void;
32
- }