@longzai-intelligence-electron/core 0.0.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.
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import"./rolldown-runtime-BqT_7tdF.js";import{t as e}from"./ipc.schema-CRktvhDm.js";import{BrowserWindow as t,ipcMain as n,session as r,shell as i}from"electron";import*as a from"zod";import{defineEnumSchema as o}from"@longzai-intelligence-zod/utils";import{join as s,resolve as c}from"node:path";const l=new Set([`operation`,`channel`,`handler`,`module`,`feature`,`action`,`phase`,`stage`,`scope`,`type`,`reason`,`status`,`code`,`count`,`total`,`size`,`limit`,`offset`,`attempt`,`retry`]),u=/(stack|trace|path|token|secret|password|key|sql|query|prompt|content|raw|payload)/i;function d(){return process.env.NODE_ENV===`development`}function f(e){return e===null||[`string`,`number`,`boolean`].includes(typeof e)}function ee(e){return u.test(e)?!1:l.has(e)?!0:/(?:^|_)(?:id|uuid)$/i.test(e)||/(?:Id|UUID|Uuid)$/.test(e)}function te(e){if(e===void 0)return;if(d())return e;let t={};for(let[n,r]of Object.entries(e))if(ee(n)){if(f(r)){t[n]=r;continue}Array.isArray(r)&&r.every(f)&&(t[n]=r.slice(0,20))}return Object.keys(t).length>0?t:void 0}function p(e){return e===void 0?{success:!0}:{success:!0,data:e}}function m(e,t,n){let r={code:e,message:t},i=te(n);return i!==void 0&&(r.details=i),{success:!1,error:r}}function h(e){return e.success===!0}function g(e){return e.success===!1}function _(e,t){if(h(e))return e.data;let n=e.error?.code?`[${e.error.code}] `:``,r=e.error?.message??t;throw Error(`${n}${r}`)}function v(e){return e instanceof a.ZodFunction}function y(e){return e instanceof a.ZodTuple}function b(e){return e instanceof a.ZodArray}function ne(e){return e.length>0}function re(e){return ne(e)?a.tuple(e):a.tuple([])}async function ie(e,t,n){return Reflect.apply(e,null,[t,...Array.isArray(n)?n:[n]])}function x(e){return(t,...n)=>e(t,...n)}function ae(e){let t=e._zod.def.input;return e=>{let n=a.core.safeParse(t,e);return n.success?{success:!0,data:n.data}:{success:!1,error:JSON.stringify(n.error.issues)}}}function S(e){return t=>{let n=y(e)||b(e)?t:[t],r=a.core.safeParse(e,y(e)||b(e)?t:n);return r.success?{success:!0,data:r.data}:{success:!1,error:JSON.stringify(r.error.issues)}}}function oe(){return(e,t)=>{let r=String(e),i=x(t);n.handle(r,i)}}function se(){return e=>{let t=String(e);n.removeHandler(t)}}function ce(e,t){n.handle(e,t)}function C(e){for(let t in e){let n=e[t];n&&ce(t,x(n))}}const w=a.object({code:e,message:a.string(),details:a.record(a.string(),a.unknown()).optional()});function T(e){return a.object({success:a.boolean(),data:e.optional(),error:w.optional()})}const E=T(a.void());function D(e,t){return a.object({params:e,return:t})}function O(e){return e}function k(e,t){return a.function({input:e,output:t})}function A(e,t){let n={},r={};for(let[i,o]of Object.entries(t)){n[i]=`${e}:${i}`;let t=re(o.input?.filter(Boolean)??[]),s=T(o.output);r[i]=a.function({input:t,output:s})}return j(n,a.object(r))}function j(e,t){return{channels:e,schema:t}}const M=a.object({success:a.boolean(),data:a.unknown().optional(),error:a.object({code:e,message:a.string(),details:a.record(a.string(),a.unknown()).optional()}).optional()});function N(e,t,r,i){let a=S(t);n.handle(e,async(e,...t)=>{let n=a(t);if(!n.success)return{success:!1,error:{code:`INVALID_INPUT`,message:`参数验证失败: ${n.error}`}};let r=Array.isArray(n.data)?[e,...n.data]:[e,n.data],o=M.safeParse(await Reflect.apply(i,null,r));return o.success?o.data:{success:!1,error:{code:`INTERNAL_ERROR`,message:`Handler 返回值类型无效`}}})}function P(e){let t=e.schema.shape,r=e.channels;return(e,i)=>{let a=String(e),o=t[a];if(!o||!v(o)){console.error(`Schema for key "${a}" is not a ZodFunction`);return}let s=ae(o),c=r[a];if(!c){console.error(`Channel for key "${a}" not found`);return}n.handle(c,async(e,...t)=>{let n=s(t);return n.success?await ie(i,e,n.data):{success:!1,error:{code:`INVALID_INPUT`,message:`参数验证失败: ${n.error}`}}})}}function F(e,t){let n=P(e);Object.entries(t).forEach(([e,t])=>{t&&n(e,t)})}function I(e){n.removeHandler(e)}function L(e){let t=e.channels;return e=>{let n=t[e];I(n)}}const R={width:1200,height:800,frame:!1,titleBarStyle:`hidden`,autoHideMenuBar:!0},z={MINIMIZE:`window:minimize`,MAXIMIZE:`window:maximize`,CLOSE:`window:close`,IS_MAXIMIZED:`window:is-maximized`};let B=null;function V(){return B}function H(){n.removeHandler(z.MINIMIZE),n.handle(z.MINIMIZE,()=>{B?.minimize()}),n.removeHandler(z.MAXIMIZE),n.handle(z.MAXIMIZE,()=>{B?.isMaximized()?B.unmaximize():B?.maximize()}),n.removeHandler(z.CLOSE),n.handle(z.CLOSE,()=>{B?.close()}),n.removeHandler(z.IS_MAXIMIZED),n.handle(z.IS_MAXIMIZED,()=>B?.isMaximized()||!1)}function le(e={}){let n={...R,...e};B=new t({width:n.width,height:n.height,minWidth:n.minWidth,minHeight:n.minHeight,frame:n.frame,titleBarStyle:n.titleBarStyle,autoHideMenuBar:n.autoHideMenuBar,show:!1,webPreferences:{preload:s(__dirname,`../preload/index.cjs`),sandbox:!1,contextIsolation:!0,webviewTag:!0,...n.browserWindowOptions?.webPreferences},...n.browserWindowOptions}),B.on(`ready-to-show`,()=>{B?.show()}),process.env.ELECTRON_RENDERER_URL?(B.loadURL(process.env.ELECTRON_RENDERER_URL),n.devTools!==!1&&B.webContents.openDevTools()):B.loadFile(s(__dirname,`../renderer/index.html`)),B.webContents.setWindowOpenHandler(e=>(i.openExternal(e.url),{action:`deny`}))}function U(){B=null}var W=class e{static instance;instances=new Map;constructor(){}static getInstance(){return e.instance||=new e,e.instance}register(e,t){this.instances.set(e,t)}resolve(e){let t=this.instances.get(e);if(!t)throw Error(`依赖 '${e}' 未注册`);return t}resolveWithGuard(e,t){let n=this.resolve(e);if(!t(n))throw Error(`依赖 '${e}' 类型守卫检查失败`);return n}has(e){return this.instances.has(e)}clear(){this.instances.clear()}};function ue(){return W.getInstance()}const G={LOGGER:`logger`,DATABASE:`database`,WINDOW_SERVICE:`window-service`,LIFECYCLE_MANAGER:`lifecycle-manager`},de={...G},K=o([`UNKNOWN`,`INVALID_ARGUMENT`,`OPERATION_FAILED`,`AUTH_FAILED`,`AUTH_UNAUTHORIZED`,`AUTH_TOKEN_EXPIRED`,`AUTH_INVALID_CREDENTIALS`,`DB_CONNECTION_ERROR`,`DB_QUERY_ERROR`,`DB_NOT_FOUND`,`DB_CONSTRAINT_VIOLATION`,`FILE_NOT_FOUND`,`FILE_READ_ERROR`,`FILE_WRITE_ERROR`,`FILE_PERMISSION_DENIED`,`GIT_NOT_A_REPO`,`GIT_COMMAND_FAILED`,`GIT_MERGE_CONFLICT`,`NETWORK_ERROR`,`NETWORK_TIMEOUT`,`PLUGIN_NOT_FOUND`,`PLUGIN_LOAD_FAILED`,`PLUGIN_EXECUTION_ERROR`],`错误码`);var q=class e extends Error{code;details;timestamp;constructor(e,t,n){super(t),this.name=`AppError`,this.code=e,this.details=n,this.timestamp=Date.now()}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,timestamp:this.timestamp,stack:this.stack}}static fromError(t,n=K.UNKNOWN){return t instanceof e?t:new e(n,t.message,{originalError:t})}static unknown(t){return new e(K.UNKNOWN,t)}static invalidArgument(t){return new e(K.INVALID_ARGUMENT,t)}static operationFailed(t){return new e(K.OPERATION_FAILED,t)}};function J(e){return{success:!0,data:e}}function Y(e,t,n){return{success:!1,error:new q(e,t,n)}}async function fe(e,t=K.OPERATION_FAILED){try{return J(await e())}catch(e){let n=e instanceof Error?e:Error(String(e)),r=q.fromError(n,t);return Y(r.code,r.message,r.details)}}const X=o([`IDLE`,`INITIALIZING`,`READY`,`SHUTTING_DOWN`],`生命周期阶段`);var Z=class{phase=X.IDLE;database=null;startupHooks=[];readyHooks=[];shutdownHooks=[];readyResolvers=[];setDatabase(e){this.database=e}getPhase(){return this.phase}isReady(){return this.phase===X.READY}getDatabase(){return this.database}onShutdown(e){this.shutdownHooks.push(e)}onBeforeStartup(e){this.startupHooks.push(e)}onReady(e){this.readyHooks.push(e)}async initialize(){if(this.phase===X.IDLE){this.phase=X.INITIALIZING;for(let e of this.startupHooks)await e();for(let e of this.readyHooks)await e();this.phase=X.READY,this.readyResolvers.forEach(e=>e()),this.readyResolvers=[]}}whenReady(){return this.phase===X.READY?Promise.resolve():new Promise(e=>{this.readyResolvers.push(e)})}async shutdown(){this.phase=X.SHUTTING_DOWN;for(let e of this.shutdownHooks)try{await e()}catch(e){console.error(`关闭钩子执行失败:`,e)}this.phase=X.IDLE,this.startupHooks=[],this.readyHooks=[],this.shutdownHooks=[],this.readyResolvers=[],this.database=null}};const pe=new Z;function Q(e,t={}){let n=t.devConnectSrc??[`http://127.0.0.1:3000`,`http://localhost:*`,`ws://localhost:*`,`wss://localhost:*`],r=t.prodConnectSrc??[`https:`,`wss:`];return e?[`default-src 'self'`,`script-src 'self' 'unsafe-inline' 'unsafe-eval' https: http:`,`style-src 'self' 'unsafe-inline' https: http:`,`img-src 'self' data: https: http:`,`connect-src 'self' ${n.join(` `)}`,`font-src 'self' https: data:`].join(`; `):[`default-src 'self'`,`script-src 'self' 'unsafe-inline' https:`,`style-src 'self' 'unsafe-inline' https:`,`img-src 'self' data: https:`,`connect-src 'self' ${r.join(` `)}`,`font-src 'self' https: data:`].join(`; `)}function me(e={}){let t=Q(process.env.ELECTRON_RENDERER_URL!==void 0,e);r.defaultSession.webRequest.onHeadersReceived((e,n)=>{n({responseHeaders:{...e.responseHeaders,"Content-Security-Policy":[t]}})})}function he(e){return{resolve:{alias:{"@shared":c(`src/shared`),"@main":c(`src/main`)}},build:{externalizeDeps:{exclude:e}}}}function ge(){return{resolve:{alias:{"@shared":c(`src/shared`),"@preload":c(`src/preload`)}},build:{externalizeDeps:{exclude:[`@electron-toolkit/preload`]},rollupOptions:{external:[`electron`],output:{entryFileNames:`[name].cjs`}}},lib:{entry:`src/preload/index.ts`,formats:[`cjs`]}}}function $(){return{resolve:{alias:{"@renderer":c(`src/renderer/src`),"@shared":c(`src/shared`)}}}}function _e(e){let{externalPackages:t=[]}=e;return{main:he(t),preload:ge(),renderer:$()}}export{q as AppError,G as CORE_TOKENS,R as DEFAULT_WINDOW_OPTIONS,W as DIContainer,W as DIContainerService,K as ErrorCode,e as IPCErrorCodeSchema,w as IPCErrorSchema,E as IPCResultSchema,Z as LifecycleManager,X as LifecyclePhase,de as REPOSITORY_TOKENS,z as WINDOW_CONTROL_CHANNELS,me as configureCSP,Q as createCSPPolicy,_e as createDesktopViteConfig,oe as createHandle,O as createIPCAPISchema,k as createIPCFunctionSchema,D as createIPCMethodDefinitionSchema,T as createIPCResultSchema,S as createParamsValidator,se as createRemove,le as createWindow,P as createZodHandle,L as createZodRemove,A as defineZodIPCSchema,U as destroyMainWindow,Y as errorFailure,J as errorSuccess,m as failure,ue as getContainer,V as getMainWindow,g as isFailure,h as isSuccess,pe as lifecycleManager,C as registerHandlers,H as registerWindowControlHandlers,N as registerZodHandler,F as registerZodHandlers,I as removeZodHandler,p as success,_ as unwrap,fe as wrapAsync};
@@ -0,0 +1 @@
1
+ import{defineEnumSchema as e}from"@longzai-intelligence-zod/utils";const t=e([`NOT_FOUND`,`VALIDATION_ERROR`,`PERMISSION_DENIED`,`INTERNAL_ERROR`,`NETWORK_ERROR`,`TIMEOUT`,`CONFLICT`,`INVALID_INPUT`,`RESOURCE_EXHAUSTED`,`UNAUTHORIZED`],`IPC错误码`);export{t};
@@ -0,0 +1,603 @@
1
+ import "./rolldown-runtime-BqT_7tdF.js";
2
+ import { C as IPCSerializable, D as IPCResult, E as IPCError, N as IPCErrorCode, P as IPCErrorCodeSchema, S as IPCReturn, T as TypedAPI, _ as IPCAPIToShortAPI, b as IPCParams, c as ZodIPCMethodsDefinition, g as IPCAPIToFunctions, h as ExtractMethodName, l as ZodIPCSchema, t as IPCResult$2, v as IPCAPIWithMapping, w as StrictIPCAPI, x as IPCParamsArray, y as IPCMethodDefinition } from "./types-DKXNvkb9.js";
3
+ import * as z from "zod";
4
+ //#region src/ipc/base/schemas.d.ts
5
+ /**
6
+ * IPC 错误 Schema
7
+ */
8
+ declare const IPCErrorSchema: z.ZodObject<{
9
+ code: z.ZodEnum<{
10
+ CONFLICT: "CONFLICT";
11
+ INTERNAL_ERROR: "INTERNAL_ERROR";
12
+ INVALID_INPUT: "INVALID_INPUT";
13
+ NETWORK_ERROR: "NETWORK_ERROR";
14
+ NOT_FOUND: "NOT_FOUND";
15
+ PERMISSION_DENIED: "PERMISSION_DENIED";
16
+ RESOURCE_EXHAUSTED: "RESOURCE_EXHAUSTED";
17
+ TIMEOUT: "TIMEOUT";
18
+ UNAUTHORIZED: "UNAUTHORIZED";
19
+ VALIDATION_ERROR: "VALIDATION_ERROR";
20
+ }>;
21
+ message: z.ZodString;
22
+ details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
23
+ }, z.core.$strip>;
24
+ /**
25
+ * IPC 错误类型
26
+ */
27
+ type IPCError$1 = z.infer<typeof IPCErrorSchema>;
28
+ /**
29
+ * IPC 结果 Schema 类型
30
+ *
31
+ * @typeParam T - 数据 Schema 类型
32
+ */
33
+ type IPCResultSchemaType<T extends z.ZodTypeAny> = z.ZodObject<{
34
+ /**
35
+ * 操作是否成功
36
+ */
37
+ success: z.ZodBoolean;
38
+ /**
39
+ * 成功时返回的数据
40
+ */
41
+ data: z.ZodOptional<T>;
42
+ /**
43
+ * 失败时的错误信息
44
+ */
45
+ error: z.ZodOptional<typeof IPCErrorSchema>;
46
+ }>;
47
+ /**
48
+ * 创建 IPC 结果 Schema 的工厂函数
49
+ *
50
+ * @typeParam T - 数据 Schema 类型
51
+ * @param dataSchema - 数据 Schema
52
+ * @returns IPC 结果 Schema
53
+ */
54
+ declare function createIPCResultSchema<T extends z.ZodTypeAny>(dataSchema: T): IPCResultSchemaType<T>;
55
+ /**
56
+ * IPC 结果 Schema(无数据)
57
+ */
58
+ declare const IPCResultSchema: IPCResultSchemaType<z.ZodVoid>;
59
+ /**
60
+ * IPC 结果类型
61
+ *
62
+ * @typeParam T - 数据类型
63
+ */
64
+ type IPCResult$1<T = void> = {
65
+ /**
66
+ * 标识操作是否成功
67
+ */
68
+ success: boolean;
69
+ /**
70
+ * 成功时返回的数据
71
+ */
72
+ data?: T;
73
+ /**
74
+ * 失败时的错误信息
75
+ */
76
+ error?: IPCError$1;
77
+ };
78
+ /**
79
+ * 创建成功结果(旧版 API,保持兼容)
80
+ *
81
+ * @deprecated 使用 `success` 替代
82
+ * @typeParam T - 数据类型
83
+ * @param data - 成功数据
84
+ * @returns 成功结果
85
+ */
86
+ declare function createSuccessResult<T>(data: T): IPCResult$1<T>;
87
+ /**
88
+ * 创建失败结果(旧版 API,保持兼容)
89
+ *
90
+ * @deprecated 使用 `failure` 替代
91
+ * @typeParam T - 数据类型
92
+ * @param code - 错误码
93
+ * @param message - 错误消息
94
+ * @param details - 错误详情
95
+ * @returns 失败结果
96
+ */
97
+ declare function createErrorResult<T>(code: IPCErrorCode, message: string, details?: Record<string, unknown>): IPCResult$1<T>;
98
+ /**
99
+ * 成功结果类型守卫(旧版 API,保持兼容)
100
+ *
101
+ * @deprecated 使用 `isSuccess` 替代
102
+ * @typeParam T - 数据类型
103
+ * @param result - IPC 结果
104
+ * @returns 是否为成功结果
105
+ */
106
+ declare function isSuccessResult<T>(result: IPCResult$1<T>): result is IPCResult$1<T> & {
107
+ /**
108
+ * 操作成功标识
109
+ */
110
+ success: true;
111
+ /**
112
+ * 成功返回的数据
113
+ */
114
+ data: T;
115
+ };
116
+ /**
117
+ * 失败结果类型守卫(旧版 API,保持兼容)
118
+ *
119
+ * @deprecated 使用 `isFailure` 替代
120
+ * @typeParam T - 数据类型
121
+ * @param result - IPC 结果
122
+ * @returns 是否为失败结果
123
+ */
124
+ declare function isErrorResult<T>(result: IPCResult$1<T>): result is IPCResult$1<T> & {
125
+ /**
126
+ * 操作失败标识
127
+ */
128
+ success: false;
129
+ /**
130
+ * 失败错误信息
131
+ */
132
+ error: IPCError$1;
133
+ };
134
+ /**
135
+ * IPC 方法定义 Schema 类型
136
+ *
137
+ * @typeParam P - 参数 Schema 类型
138
+ * @typeParam R - 返回值 Schema 类型
139
+ */
140
+ type IPCMethodDefinitionSchemaType<P extends z.ZodTypeAny, R extends z.ZodTypeAny> = z.ZodObject<{
141
+ /**
142
+ * 方法参数 Schema
143
+ */
144
+ params: P;
145
+ /**
146
+ * 方法返回值 Schema
147
+ */
148
+ return: R;
149
+ }>;
150
+ /**
151
+ * IPC 方法定义 Schema 工厂
152
+ *
153
+ * @typeParam P - 参数 Schema 类型
154
+ * @typeParam R - 返回值 Schema 类型
155
+ * @param paramsSchema - 参数 Schema
156
+ * @param returnSchema - 返回值 Schema
157
+ * @returns IPC 方法定义 Schema
158
+ */
159
+ declare function createIPCMethodDefinitionSchema<P extends z.ZodTypeAny, R extends z.ZodTypeAny>(paramsSchema: P, returnSchema: R): IPCMethodDefinitionSchemaType<P, R>;
160
+ /**
161
+ * IPC 方法定义类型
162
+ *
163
+ * @typeParam P - 参数类型
164
+ * @typeParam R - 返回类型
165
+ */
166
+ type IPCMethodDefinition$1<P extends readonly unknown[] = readonly unknown[], R = unknown> = {
167
+ /**
168
+ * 方法参数类型的只读数组
169
+ */
170
+ params: P;
171
+ /**
172
+ * 方法返回值类型
173
+ */
174
+ return: R;
175
+ };
176
+ /**
177
+ * 创建 IPC API Schema 的工厂函数
178
+ *
179
+ * @typeParam T - API Schema 类型
180
+ * @param apiSchema - API Schema 定义
181
+ * @returns IPC API Schema
182
+ */
183
+ declare function createIPCAPISchema<T extends z.ZodObject<Record<string, z.ZodTypeAny>>>(apiSchema: T): T;
184
+ //#endregion
185
+ //#region src/ipc/preload/typed-ipc.utils.d.ts
186
+ /**
187
+ * 类型安全的 API 返回类型
188
+ *
189
+ * @typeParam T - API 类型
190
+ * @typeParam K - 键名
191
+ */
192
+ type TypedAPIFunction<T, K extends keyof T> = T[K] extends IPCMethodDefinition<infer P, infer R> ? (...args: [...P]) => Promise<R> : T[K] extends ((...args: infer A) => Promise<infer R>) ? (...args: A) => Promise<R> : never;
193
+ /**
194
+ * 类型安全的 API 对象类型
195
+ *
196
+ * @typeParam T - API 类型
197
+ * @typeParam M - 映射类型
198
+ */
199
+ type TypedAPIObject<T extends Record<string, unknown>, M extends Record<string, keyof T>> = { [K in keyof M]: TypedAPIFunction<T, M[K]>; };
200
+ /**
201
+ * 强类型的 IPC invoke
202
+ *
203
+ * 自动推断参数和返回类型
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * interface MyIPCAPI extends StrictIPCAPI {
208
+ * 'agent:delete': {
209
+ * params: readonly [id: string];
210
+ * return: boolean;
211
+ * };
212
+ * }
213
+ *
214
+ * const result = await invoke<MyIPCAPI, 'agent:delete'>('agent:delete', 'agent-123');
215
+ * // result 自动推断为 boolean
216
+ * ```;
217
+ *
218
+ * @typeParam T - IPC API 定义类型,必须继承 StrictIPCAPI
219
+ * @typeParam K - 方法键名
220
+ * @param channel - IPC 通道名称
221
+ * @param args - 参数列表
222
+ * @returns Promise 包含返回值
223
+ */
224
+ declare function invoke<T extends StrictIPCAPI, K extends keyof T>(channel: K, ...args: IPCParamsArray<T[K]>): Promise<IPCReturn<T[K]>>;
225
+ /**
226
+ * 创建类型安全的 API 对象(支持 IPCMethodDefinition 和函数签名两种格式)
227
+ *
228
+ * T 为 IPC API 定义类型
229
+ *
230
+ * 注意:此函数返回类型安全的 API 对象,类型安全由 TypeScript 编译时保证。
231
+ * 运行时会创建实际的 IPC 调用函数。
232
+ *
233
+ * @example
234
+ * ```typescript
235
+ * // IPCMethodDefinition 格式
236
+ * interface MyIPCAPI extends StrictIPCAPI {
237
+ * 'agent:getAll': {
238
+ * params: readonly [];
239
+ * return: Agent[];
240
+ * };
241
+ * 'agent:delete': {
242
+ * params: readonly [id: string];
243
+ * return: boolean;
244
+ * };
245
+ * }
246
+ *
247
+ * const agentAPI = createTypedAPI<MyIPCAPI>({
248
+ * getAll: 'agent:getAll',
249
+ * delete: 'agent:delete',
250
+ * });
251
+ *
252
+ * // 完全类型安全
253
+ * const agents = await agentAPI.getAll();
254
+ * await agentAPI.delete('agent-123');
255
+ * ```;
256
+ *
257
+ * @example
258
+ * ```typescript
259
+ * // 函数签名格式
260
+ * interface AuthIPCAPI {
261
+ * login: (username: string, password: string) => Promise<User>;
262
+ * logout: () => Promise<void>;
263
+ * }
264
+ *
265
+ * const authAPI = createTypedAPI<AuthIPCAPI>({
266
+ * login: 'auth:login',
267
+ * logout: 'auth:logout',
268
+ * });
269
+ *
270
+ * // 完全类型安全
271
+ * const user = await authAPI.login('username', 'password');
272
+ * await authAPI.logout();
273
+ * ```;
274
+ *
275
+ * @typeParam T - IPC API 定义类型
276
+ * @param mapping - 方法名到通道名的映射
277
+ * @returns 类型安全的 API 对象
278
+ */
279
+ declare function createTypedAPI<T extends Record<string, unknown>>(mapping: Record<string, keyof T>): TypedAPIObject<T, Record<string, keyof T>>;
280
+ /**
281
+ * IPC 事件监听器类型
282
+ *
283
+ * @typeParam TPayload - 事件负载类型
284
+ */
285
+ type IPCEventListener$1<TPayload> = (payload: TPayload) => void;
286
+ /**
287
+ * 取消订阅函数类型
288
+ */
289
+ type UnsubscribeFunction$1 = () => void;
290
+ /**
291
+ * 订阅 IPC 事件通道
292
+ *
293
+ * @typeParam TPayload - 事件负载类型
294
+ * @param channel - 事件通道名称
295
+ * @param listener - 事件处理函数
296
+ * @returns 取消订阅函数
297
+ */
298
+ declare function subscribeChannel<TPayload>(channel: string, listener: IPCEventListener$1<TPayload>): UnsubscribeFunction$1;
299
+ //#endregion
300
+ //#region src/ipc/zod/preload/helpers.d.ts
301
+ /**
302
+ * 验证结果类型
303
+ *
304
+ * @typeParam T - 验证结果的数据类型
305
+ */
306
+ type ValidationResult<T> = {
307
+ /**
308
+ * 验证成功标识
309
+ */
310
+ success: true;
311
+ /**
312
+ * 验证后的数据
313
+ */
314
+ data: T;
315
+ } | {
316
+ /**
317
+ * 验证失败标识
318
+ */
319
+ success: false;
320
+ /**
321
+ * 错误信息
322
+ */
323
+ error: string;
324
+ };
325
+ /**
326
+ * 输出验证器函数类型
327
+ *
328
+ * @typeParam R - 输出 Schema 类型
329
+ */
330
+ type OutputValidatorFn<R> = (result: unknown) => Promise<ValidationResult<R>>;
331
+ //#endregion
332
+ //#region src/ipc/zod/preload/types.d.ts
333
+ /**
334
+ * Zod API Schema 类型
335
+ *
336
+ * 使用正确的泛型约束,避免使用 any
337
+ */
338
+ type ZodAPISchema = z.ZodObject<Record<string, z.ZodType>>;
339
+ /**
340
+ * 类型安全的 API 对象类型
341
+ *
342
+ * @typeParam T - Zod Object Schema 类型
343
+ */
344
+ type ZodAPIObject<T extends ZodAPISchema> = z.infer<T>;
345
+ /**
346
+ * 类型安全的 API 函数类型
347
+ *
348
+ * @typeParam T - Zod Function Schema 类型
349
+ */
350
+ type ZodAPIFunction<T extends z.ZodFunction> = z.infer<T>;
351
+ /**
352
+ * IPC 事件监听器类型
353
+ *
354
+ * @typeParam TPayload - 事件负载类型
355
+ */
356
+ type IPCEventListener<TPayload> = (payload: TPayload) => void;
357
+ /**
358
+ * 取消订阅函数类型
359
+ */
360
+ type UnsubscribeFunction = () => void;
361
+ /**
362
+ * 从 ZodIPCSchema 中提取 ZodFunction 类型(Preload 版本)
363
+ *
364
+ * 条件类型:匹配包含 input(输入参数 Schema 数组)和 output(输出结果 Schema)属性的结构
365
+ *
366
+ * @typeParam T - ZodIPCMethodsDefinition 类型
367
+ * @typeParam K - 方法键名
368
+ */
369
+ type ExtractZodFunctionFromIPCSchema$1<T extends ZodIPCMethodsDefinition, K extends keyof T> = T[K] extends {
370
+ /**
371
+ * 输入参数 Schema 数组
372
+ */
373
+ input?: infer I;
374
+ /**
375
+ * 输出结果 Schema
376
+ */
377
+ output: unknown;
378
+ } ? I extends z.ZodTypeAny[] ? z.ZodFunction<z.ZodTuple<{ [Index in keyof I]: I[Index]; }>, z.ZodPromise<z.ZodUnknown>> : z.ZodFunction<z.ZodTuple<[]>, z.ZodPromise<z.ZodUnknown>> : never;
379
+ /**
380
+ * 从 ZodFunction Schema 提取参数元组类型
381
+ *
382
+ * @typeParam F - ZodFunction 类型
383
+ */
384
+ type ExtractAPIArgs$1<F> = F extends z.ZodFunction<infer I, infer _> ? I extends z.ZodTuple<infer Items> ? { [K in keyof Items]: z.infer<Items[K]>; } : [] : unknown[];
385
+ /**
386
+ * 类型安全的 API 函数类型(Preload 版本)
387
+ *
388
+ * @typeParam F - ZodFunction Schema 类型
389
+ */
390
+ type TypedAPIFn$1<F extends z.ZodFunction> = (...args: ExtractAPIArgs$1<F>) => Promise<unknown>;
391
+ /**
392
+ * ZodIPCSchema API 对象类型
393
+ *
394
+ * @typeParam T - ZodIPCMethodsDefinition 类型
395
+ */
396
+ type ZodIPCSchemaAPIObject<T extends ZodIPCMethodsDefinition> = { [K in keyof T & string]: TypedAPIFn$1<ExtractZodFunctionFromIPCSchema$1<T, K>>; };
397
+ /**
398
+ * 带验证的 ZodIPCSchema API 返回类型
399
+ *
400
+ * @typeParam T - ZodIPCMethodsDefinition 类型
401
+ */
402
+ type ValidatedZodIPCSchemaResult<T extends ZodIPCMethodsDefinition> = {
403
+ /**
404
+ * 类型安全的 API 对象
405
+ */
406
+ api: ZodIPCSchemaAPIObject<T>;
407
+ /**
408
+ * 验证返回值的函数
409
+ */
410
+ validate: <K extends keyof T & string>(key: K, result: unknown) => ValidationResult<unknown>;
411
+ };
412
+ //#endregion
413
+ //#region src/ipc/zod/preload/api.utils.d.ts
414
+ /**
415
+ * 从 ZodIPCSchema 中提取 ZodFunction 类型(Preload 版本)
416
+ *
417
+ * 条件类型:匹配包含 input(输入参数 Schema 数组)和 output(输出结果 Schema)属性的结构
418
+ *
419
+ * @typeParam T - ZodIPCMethodsDefinition 类型
420
+ * @typeParam K - 方法键名
421
+ */
422
+ type ExtractZodFunctionFromIPCSchema<T extends ZodIPCMethodsDefinition, K extends keyof T> = T[K] extends {
423
+ /**
424
+ * 输入参数 Schema 数组
425
+ */
426
+ input?: infer I;
427
+ /**
428
+ * 输出结果 Schema
429
+ */
430
+ output: unknown;
431
+ } ? I extends z.ZodTypeAny[] ? z.ZodFunction<z.ZodTuple<{ [Index in keyof I]: I[Index]; }>, z.ZodPromise<z.ZodUnknown>> : z.ZodFunction<z.ZodTuple<[]>, z.ZodPromise<z.ZodUnknown>> : never;
432
+ /**
433
+ * 从 ZodFunction Schema 提取参数元组类型
434
+ *
435
+ * @typeParam F - ZodFunction 类型
436
+ */
437
+ type ExtractAPIArgs<F> = F extends z.ZodFunction<infer I, infer _> ? I extends z.ZodTuple<infer Items> ? { [K in keyof Items]: z.infer<Items[K]>; } : [] : unknown[];
438
+ /**
439
+ * 类型安全的 API 函数类型(Preload 版本)
440
+ *
441
+ * @typeParam F - ZodFunction Schema 类型
442
+ */
443
+ type TypedAPIFn<F extends z.ZodFunction> = (...args: ExtractAPIArgs<F>) => Promise<unknown>;
444
+ /**
445
+ * ZodIPCSchema API 对象类型
446
+ *
447
+ * @typeParam T - ZodIPCMethodsDefinition 类型
448
+ */
449
+ type ZodIPCSchemaAPIObject$1<T extends ZodIPCMethodsDefinition> = { [K in keyof T & string]: TypedAPIFn<ExtractZodFunctionFromIPCSchema<T, K>>; };
450
+ /**
451
+ * 带验证的 ZodIPCSchema API 返回类型
452
+ *
453
+ * @typeParam T - ZodIPCMethodsDefinition 类型
454
+ */
455
+ type ValidatedZodIPCSchemaResult$1<T extends ZodIPCMethodsDefinition> = {
456
+ /**
457
+ * 类型安全的 API 对象
458
+ */
459
+ api: ZodIPCSchemaAPIObject$1<T>;
460
+ /**
461
+ * 验证返回值的函数
462
+ */
463
+ validate: <K extends keyof T & string>(key: K, result: unknown) => Promise<ValidationResult<unknown>>;
464
+ };
465
+ /**
466
+ * 创建 Zod 验证的类型安全 API
467
+ *
468
+ * 从 ZodIPCSchema 创建类型安全的 API 对象,通道名从 schema.channels 自动获取
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * const AgentIPCAPISchema = defineZodIPCSchema('agent', {
473
+ * getAll: { output: z.array(AgentSchema) },
474
+ * getById: { input: [z.string()], output: AgentSchema.nullable() },
475
+ * create: { input: [AgentCreateParamsSchema], output: AgentSchema },
476
+ * delete: { input: [z.string()], output: z.void() },
477
+ * });
478
+ *
479
+ * // 通道名自动推导
480
+ * AgentIPCAPISchema.channels.getAll; // 'agent:getAll'
481
+ *
482
+ * // Preload 进程使用(无需传递通道映射)
483
+ * const agentAPI = createZodAPI(AgentIPCAPISchema);
484
+ *
485
+ * // 完全类型安全
486
+ * const result = await agentAPI.getAll();
487
+ * ```;
488
+ *
489
+ * @typeParam T - ZodIPCMethodsDefinition 类型
490
+ * @param ipcSchema - ZodIPCSchema 对象(由 defineZodIPCSchema 创建)
491
+ * @returns 类型安全的 API 对象
492
+ */
493
+ declare function createZodAPI<T extends ZodIPCMethodsDefinition>(ipcSchema: ZodIPCSchema<T>): ZodIPCSchemaAPIObject$1<T>;
494
+ /**
495
+ * 创建带运行时验证的类型安全 API
496
+ *
497
+ * 返回的 API 对象会在每次调用后验证返回值类型
498
+ *
499
+ * @example
500
+ * ```typescript
501
+ * const AgentIPCAPISchema = defineZodIPCSchema('agent', {
502
+ * getAll: { output: z.array(AgentSchema) },
503
+ * });
504
+ *
505
+ * const { api, validate } = createValidatedAPI(AgentIPCAPISchema);
506
+ *
507
+ * const result = await api.getAll();
508
+ * if (result.success) {
509
+ * console.log(result.data);
510
+ * }
511
+ * ```;
512
+ *
513
+ * @typeParam T - ZodIPCMethodsDefinition 类型
514
+ * @param ipcSchema - ZodIPCSchema 对象
515
+ * @returns 包含 API 对象和验证函数的对象
516
+ * @throws {@link Error} 当输出验证失败时抛出错误
517
+ */
518
+ declare function createValidatedAPI<T extends ZodIPCMethodsDefinition>(ipcSchema: ZodIPCSchema<T>): ValidatedZodIPCSchemaResult$1<T>;
519
+ /**
520
+ * 订阅 IPC 事件通道(带 Zod 验证)
521
+ *
522
+ * @example
523
+ * ```typescript
524
+ * const MessageSchema = z.object({
525
+ * id: z.string(),
526
+ * content: z.string(),
527
+ * });
528
+ *
529
+ * const unsubscribe = subscribeZodChannel('chat:message', MessageSchema, (message) => {
530
+ * console.log(message.content); // 类型安全
531
+ * });
532
+ * ```;
533
+ *
534
+ * @typeParam T - 负载 Schema 类型
535
+ * @param channel - 事件通道名称
536
+ * @param schema - 负载 Zod Schema
537
+ * @param listener - 事件处理函数
538
+ * @returns 取消订阅函数
539
+ */
540
+ declare function subscribeZodChannel<T extends z.ZodType>(channel: string, schema: T, listener: IPCEventListener<z.infer<T>>): UnsubscribeFunction;
541
+ /**
542
+ * 强类型的 IPC invoke(带 Zod 验证)
543
+ *
544
+ * @typeParam T - 返回值 Schema 类型
545
+ * @param channel - IPC 通道名称
546
+ * @param schema - 返回值 Zod Schema
547
+ * @param args - 参数列表
548
+ * @returns Promise 包含验证后的返回值
549
+ */
550
+ declare function invokeZod<T extends z.ZodType>(channel: string, schema: T, ...args: unknown[]): Promise<z.infer<T>>;
551
+ /**
552
+ * 安全的 IPC invoke(返回验证结果)
553
+ *
554
+ * @typeParam T - 返回值 Schema 类型
555
+ * @param channel - IPC 通道名称
556
+ * @param schema - 返回值 Zod Schema
557
+ * @param args - 参数列表
558
+ * @returns Promise 包含验证结果
559
+ */
560
+ declare function safeInvokeZod<T extends z.ZodType>(channel: string, schema: T, ...args: unknown[]): Promise<ValidationResult<z.infer<T>>>;
561
+ //#endregion
562
+ //#region src/ipc/base/result.types.d.ts
563
+ /**
564
+ * 解包 IPCResult 并返回成功数据
565
+ *
566
+ * @typeParam T - 数据类型
567
+ * @param result - IPC 结果
568
+ * @param fallbackMessage - 兜底错误消息
569
+ * @returns 成功数据
570
+ * @throws {@link Error} 当结果为失败时抛出错误
571
+ */
572
+ declare function unwrapIPCResult<T>(result: IPCResult$2<T>, fallbackMessage: string): T;
573
+ //#endregion
574
+ //#region src/preload/safe-expose.utils.d.ts
575
+ /**
576
+ * Preload 安全暴露工具
577
+ */
578
+ type ExposedAPIValue = Record<string, unknown>;
579
+ /**
580
+ * 安全暴露 API 的配置选项
581
+ */
582
+ type ExposeSafeAPIOptions = {
583
+ /**
584
+ * 挂载到全局对象的键名
585
+ */
586
+ globalKey: string;
587
+ /**
588
+ * 需要暴露的 API 对象
589
+ */
590
+ api: ExposedAPIValue;
591
+ /**
592
+ * 实际执行暴露操作的函数
593
+ */
594
+ expose: (globalKey: string, api: ExposedAPIValue) => void;
595
+ };
596
+ /**
597
+ * 安全暴露 API 到渲染进程
598
+ *
599
+ * @param options - 安全暴露配置
600
+ */
601
+ declare function exposeSafeAPI(options: ExposeSafeAPIOptions): void;
602
+ //#endregion
603
+ export { type ExtractMethodName, type IPCAPIToFunctions, type IPCAPIToShortAPI, type IPCAPIWithMapping, type IPCError, IPCErrorCodeSchema, IPCErrorSchema, type IPCError$1 as IPCErrorZod, type IPCEventListener, type IPCMethodDefinition, type IPCMethodDefinition$1 as IPCMethodDefinitionZod, type IPCParams, type IPCParamsArray, type IPCResult, IPCResultSchema, type IPCResult$1 as IPCResultZod, type IPCReturn, type IPCSerializable, type OutputValidatorFn, type StrictIPCAPI, type TypedAPI, type TypedAPIFunction, type TypedAPIObject, type UnsubscribeFunction, type ValidatedZodIPCSchemaResult, type ValidationResult, type ZodAPIFunction, type ZodAPIObject, type ZodAPISchema, type ZodIPCSchemaAPIObject, createErrorResult, createIPCAPISchema, createIPCMethodDefinitionSchema, createIPCResultSchema, createSuccessResult, createTypedAPI, createValidatedAPI, createZodAPI, exposeSafeAPI, invoke, invokeZod, isErrorResult, isSuccessResult, safeInvokeZod, subscribeChannel, subscribeZodChannel, unwrapIPCResult };
@@ -0,0 +1 @@
1
+ import"./rolldown-runtime-BqT_7tdF.js";import{t as e}from"./ipc.schema-CRktvhDm.js";import{ipcRenderer as t}from"electron";import*as n from"zod";const r=n.object({code:e,message:n.string(),details:n.record(n.string(),n.unknown()).optional()});function i(e){return n.object({success:n.boolean(),data:e.optional(),error:r.optional()})}const a=i(n.void());function o(e){return{success:!0,data:e}}function s(e,t,n){return{success:!1,error:{code:e,message:t,details:n}}}function c(e){return e.success}function l(e){return!e.success}function u(e,t){return n.object({params:e,return:t})}function d(e){return e}function f(e,...n){let r=String(e);return t.invoke(r,...n)}function p(e){let n=Object.keys(e),r={};for(let i of n){let n=e[i],a=String(n);r[i]=(...e)=>t.invoke(a,...e)}return r}function m(e,n){let r=(e,t)=>{n(t)};return t.on(e,r),()=>{t.removeListener(e,r)}}function h(e){return e instanceof n.ZodFunction}function g(e){return e instanceof n.ZodPromise}function _(e){let t=e._zod.def.output;return g(t)&&(t=t._zod.def.innerType),async e=>{let r=await n.core.safeParseAsync(t,e);return r.success?{success:!0,data:r.data}:{success:!1,error:JSON.stringify(r.error.issues)}}}async function v(e,n,...r){let i=await t.invoke(e,...r),a=await _(n)(i);if(a.success)return a.data;throw Error(`Output validation failed: ${a.error}`)}function y(e){let n=e.schema.shape,r=e.channels,i={};for(let e of Object.keys(n)){let a=n[e];if(a&&h(a)){let n=r[e];n&&(i[e]=(...e)=>t.invoke(n,...e))}}return i}function b(e){let t=e.schema.shape,n=e.channels,r={};for(let e of Object.keys(t)){let i=t[e];if(i&&h(i)){let t=n[e];t&&(r[e]=(...e)=>v(t,i,...e))}}return{api:r,validate:async(e,n)=>{let r=t[String(e)];return r&&h(r)?_(r)(n):{success:!1,error:`Invalid schema`}}}}function x(e,r,i){let a=(t,a)=>{let o=n.core.safeParse(r,a);o.success?i(o.data):console.error(`Invalid payload for channel ${e}:`,a)};return t.on(e,a),()=>{t.removeListener(e,a)}}function S(e,r,...i){return t.invoke(e,...i).then(e=>n.core.parse(r,e))}async function C(e,r,...i){try{let a=await t.invoke(e,...i),o=n.core.safeParse(r,a);return o.success?{success:!0,data:o.data}:{success:!1,error:JSON.stringify(o.error.issues)}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}function w(e){return e.success}function T(e,t){if(w(e))return e.data;let n=e.error?.code?`[${e.error.code}] `:``,r=e.error?.message??t;throw Error(`${n}${r}`)}const E=new Set([`ipcRenderer`]),D=new Set([`on`,`send`,`invoke`]);function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k(e,t=`root`){for(let[n,r]of Object.entries(e)){if(E.has(n))throw Error(`禁止暴露危险键:${t}.${n}`);if(n===`ipc`&&O(r)){for(let e of Object.keys(r))if(D.has(e))throw Error(`禁止暴露通用 IPC 方法:${t}.${n}.${e}`)}O(r)&&k(r,`${t}.${n}`)}}function A(e){k(e.api),e.expose(e.globalKey,e.api)}export{e as IPCErrorCodeSchema,r as IPCErrorSchema,a as IPCResultSchema,s as createErrorResult,d as createIPCAPISchema,u as createIPCMethodDefinitionSchema,i as createIPCResultSchema,o as createSuccessResult,p as createTypedAPI,b as createValidatedAPI,y as createZodAPI,A as exposeSafeAPI,f as invoke,S as invokeZod,l as isErrorResult,c as isSuccessResult,C as safeInvokeZod,m as subscribeChannel,x as subscribeZodChannel,T as unwrapIPCResult};
@@ -0,0 +1 @@
1
+ import"node:module";export{};