@eworkbase/sdk 0.8.5 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ import { t as DEFAULT_VIEW_STATE_TOPIC } from "../host-services-cIH3aYQD.js";
2
+ import { n as defineWorkbasePluginUi } from "../ui-DGLeDJDe.js";
3
+ import { n as PluginErrorBoundary } from "../components-DxL-99bM.js";
4
+ import { initializeWorkbaseUiStyles } from "./theme.js";
5
+ import { Fragment, useCallback, useEffect, useRef, useState } from "react";
6
+ import { jsx } from "react/jsx-runtime";
7
+ //#region src/ui/hooks.tsx
8
+ /**
9
+ * React view mounting, state-sync subscription and serialized action hooks for Workbase plugins.
10
+ */
11
+ const DEFAULT_ROOT_ELEMENT_ID = "root";
12
+ const DEFAULT_LOAD_ERROR = "插件数据读取失败,请重试。";
13
+ /** Mounts a Workbase plugin view with shared style nonce, error boundary and workspace key isolation. */
14
+ function mountPluginView(options) {
15
+ const { createRoot, elementId = DEFAULT_ROOT_ELEMENT_ID, errorTitle, errorScope, errorRecovery, keyFor = buildViewContextKey, wrap, render } = options;
16
+ const container = document.getElementById(elementId);
17
+ if (!container) throw new Error(`插件视图挂载节点 #${elementId} 不存在。`);
18
+ initializeWorkbaseUiStyles();
19
+ const root = createRoot(container);
20
+ const host = defineWorkbasePluginUi({ onInit(initialization) {
21
+ const contextKey = keyFor(initialization);
22
+ const content = /* @__PURE__ */ jsx(PluginErrorBoundary, {
23
+ title: errorTitle,
24
+ scope: errorScope,
25
+ recovery: errorRecovery,
26
+ children: /* @__PURE__ */ jsx(Fragment, { children: render({
27
+ host,
28
+ initialization,
29
+ contextKey
30
+ }) }, contextKey)
31
+ });
32
+ root.render(wrap ? wrap(content) : content);
33
+ } });
34
+ return host;
35
+ }
36
+ /**
37
+ * Manages cached view state, stale-response protection, in-flight deduplication,
38
+ * backend State Sync pushes, file-change notifications and visibility-aware polling.
39
+ */
40
+ function usePluginViewState(options) {
41
+ const { host, initialState = null, stateTopic = DEFAULT_VIEW_STATE_TOPIC, refreshOnFocus = false, refreshOnFilesChanged = false, observeVisibility = false, focusCooldownMs = 0, fallbackError = DEFAULT_LOAD_ERROR, loadOnMount = !observeVisibility } = options;
42
+ const [viewElement, setViewElement] = useState(null);
43
+ const mountedRef = useRef(true);
44
+ const requestVersionRef = useRef(0);
45
+ const pendingRef = useRef(null);
46
+ const lastReadAtRef = useRef(0);
47
+ const dataRef = useRef(initialState);
48
+ const loadRef = useRef(options.load);
49
+ const onStateRef = useRef(options.onState);
50
+ const pollIntervalRef = useRef(options.pollIntervalMs);
51
+ const isBlockedRef = useRef(options.isBlocked);
52
+ loadRef.current = options.load;
53
+ onStateRef.current = options.onState;
54
+ pollIntervalRef.current = options.pollIntervalMs;
55
+ isBlockedRef.current = options.isBlocked;
56
+ const [data, setData] = useState(initialState);
57
+ const [error, setError] = useState(null);
58
+ const [isRefreshing, setIsRefreshing] = useState(false);
59
+ const [isVisible, setIsVisible] = useState(!observeVisibility);
60
+ const acceptData = useCallback((next) => {
61
+ const previous = dataRef.current;
62
+ dataRef.current = next;
63
+ lastReadAtRef.current = Date.now();
64
+ requestVersionRef.current += 1;
65
+ setData(next);
66
+ setError(null);
67
+ onStateRef.current?.(next, previous);
68
+ }, []);
69
+ const invalidatePending = useCallback(() => {
70
+ requestVersionRef.current += 1;
71
+ pendingRef.current = null;
72
+ setIsRefreshing(false);
73
+ }, []);
74
+ const clearError = useCallback(() => setError(null), []);
75
+ const refresh = useCallback(async () => {
76
+ if (pendingRef.current) return pendingRef.current;
77
+ if (!mountedRef.current || isBlockedRef.current?.()) return null;
78
+ const version = requestVersionRef.current;
79
+ setIsRefreshing(true);
80
+ const emit = (partial) => {
81
+ if (!mountedRef.current || requestVersionRef.current !== version) return;
82
+ const previous = dataRef.current;
83
+ dataRef.current = partial;
84
+ setData(partial);
85
+ onStateRef.current?.(partial, previous);
86
+ };
87
+ const request = (async () => {
88
+ try {
89
+ const next = await loadRef.current(emit);
90
+ if (!mountedRef.current || requestVersionRef.current !== version) return null;
91
+ const previous = dataRef.current;
92
+ dataRef.current = next;
93
+ lastReadAtRef.current = Date.now();
94
+ setData(next);
95
+ setError(null);
96
+ onStateRef.current?.(next, previous);
97
+ return next;
98
+ } catch (failure) {
99
+ if (mountedRef.current && requestVersionRef.current === version) setError(readableErrorMessage(failure, fallbackError));
100
+ return null;
101
+ } finally {
102
+ if (requestVersionRef.current === version) {
103
+ pendingRef.current = null;
104
+ if (mountedRef.current) setIsRefreshing(false);
105
+ }
106
+ }
107
+ })();
108
+ pendingRef.current = request;
109
+ return request;
110
+ }, [fallbackError]);
111
+ useEffect(() => {
112
+ mountedRef.current = true;
113
+ return () => {
114
+ mountedRef.current = false;
115
+ requestVersionRef.current += 1;
116
+ pendingRef.current = null;
117
+ };
118
+ }, []);
119
+ useEffect(() => {
120
+ if (loadOnMount) refresh();
121
+ }, [loadOnMount, refresh]);
122
+ useEffect(() => {
123
+ if (stateTopic === null || typeof host.view.onStateChanged !== "function") return;
124
+ return host.view.onStateChanged((pushed) => {
125
+ if (!mountedRef.current) return;
126
+ acceptData(pushed);
127
+ }, stateTopic);
128
+ }, [
129
+ acceptData,
130
+ host,
131
+ stateTopic
132
+ ]);
133
+ useEffect(() => {
134
+ if (!refreshOnFilesChanged || typeof host.view.onFilesChanged !== "function") return;
135
+ return host.view.onFilesChanged(() => {
136
+ refresh();
137
+ });
138
+ }, [
139
+ host,
140
+ refresh,
141
+ refreshOnFilesChanged
142
+ ]);
143
+ useEffect(() => {
144
+ if (!observeVisibility) {
145
+ setIsVisible(true);
146
+ return;
147
+ }
148
+ let isIntersecting = false;
149
+ const syncVisibility = () => setIsVisible(isIntersecting && document.visibilityState === "visible");
150
+ const observer = new IntersectionObserver(([entry]) => {
151
+ isIntersecting = Boolean(entry?.isIntersecting);
152
+ syncVisibility();
153
+ });
154
+ if (viewElement) observer.observe(viewElement);
155
+ document.addEventListener("visibilitychange", syncVisibility);
156
+ return () => {
157
+ observer.disconnect();
158
+ document.removeEventListener("visibilitychange", syncVisibility);
159
+ };
160
+ }, [observeVisibility, viewElement]);
161
+ useEffect(() => {
162
+ if (!isVisible) return;
163
+ const triggerRefresh = () => {
164
+ if (document.visibilityState !== "visible") return;
165
+ if (isBlockedRef.current?.()) return;
166
+ if (focusCooldownMs > 0 && Date.now() - lastReadAtRef.current < focusCooldownMs) return;
167
+ refresh();
168
+ };
169
+ if (observeVisibility) triggerRefresh();
170
+ if (!refreshOnFocus) return;
171
+ window.addEventListener("focus", triggerRefresh);
172
+ if (!observeVisibility) document.addEventListener("visibilitychange", triggerRefresh);
173
+ return () => {
174
+ window.removeEventListener("focus", triggerRefresh);
175
+ if (!observeVisibility) document.removeEventListener("visibilitychange", triggerRefresh);
176
+ };
177
+ }, [
178
+ focusCooldownMs,
179
+ isVisible,
180
+ observeVisibility,
181
+ refresh,
182
+ refreshOnFocus
183
+ ]);
184
+ useEffect(() => {
185
+ if (!isVisible) return;
186
+ const resolver = pollIntervalRef.current;
187
+ const interval = typeof resolver === "function" ? resolver(data, error) : resolver;
188
+ if (typeof interval !== "number" || interval <= 0) return;
189
+ const delay = interval;
190
+ let cancelled = false;
191
+ let timer = window.setTimeout(poll, delay);
192
+ async function poll() {
193
+ await refresh();
194
+ if (!cancelled) timer = window.setTimeout(poll, delay);
195
+ }
196
+ return () => {
197
+ cancelled = true;
198
+ window.clearTimeout(timer);
199
+ };
200
+ }, [
201
+ data,
202
+ error,
203
+ isVisible,
204
+ refresh
205
+ ]);
206
+ return {
207
+ data,
208
+ error,
209
+ isRefreshing,
210
+ isVisible,
211
+ viewRef: setViewElement,
212
+ setError,
213
+ clearError,
214
+ refresh,
215
+ acceptData,
216
+ invalidatePending
217
+ };
218
+ }
219
+ /** Serializes mutating plugin actions so concurrent clicks never overlap or leak stale errors. */
220
+ function usePluginAction(options = {}) {
221
+ const { fallbackError = "操作未完成,请重试。" } = options;
222
+ const mountedRef = useRef(true);
223
+ const isBusyRef = useRef(false);
224
+ const onErrorRef = useRef(options.onError);
225
+ onErrorRef.current = options.onError;
226
+ const [busyAction, setBusyAction] = useState(null);
227
+ useEffect(() => {
228
+ mountedRef.current = true;
229
+ return () => {
230
+ mountedRef.current = false;
231
+ };
232
+ }, []);
233
+ const run = useCallback(async (actionId, task) => {
234
+ if (!mountedRef.current || isBusyRef.current) return;
235
+ isBusyRef.current = true;
236
+ setBusyAction(actionId);
237
+ try {
238
+ return await task();
239
+ } catch (failure) {
240
+ if (mountedRef.current) onErrorRef.current?.(readableErrorMessage(failure, fallbackError));
241
+ return;
242
+ } finally {
243
+ isBusyRef.current = false;
244
+ if (mountedRef.current) setBusyAction(null);
245
+ }
246
+ }, [fallbackError]);
247
+ return {
248
+ busyAction,
249
+ isBusy: busyAction !== null,
250
+ isBusyRef,
251
+ isMountedRef: mountedRef,
252
+ run
253
+ };
254
+ }
255
+ function buildViewContextKey(payload) {
256
+ return `${payload.project.id}:${payload.workspace.id}:${payload.activationGeneration ?? 0}`;
257
+ }
258
+ function readableErrorMessage(error, fallback) {
259
+ return error instanceof Error && error.message.trim() ? error.message : fallback;
260
+ }
261
+ //#endregion
262
+ export { buildViewContextKey, mountPluginView, usePluginAction, usePluginViewState };
@@ -1,4 +1,5 @@
1
- import { A as PluginUiViewIdentity, C as PluginUiRepositoryPushOutcome, D as PluginUiToastOptions, E as PluginUiStatus, M as WorkbasePluginUiDefinition, O as PluginUiTransportConnection, S as PluginUiPromptType, T as PluginUiRepositoryPushTarget, _ as PluginUiNavigateOptions, a as PluginUiContextIdentity, b as PluginUiPromptChoice, c as PluginUiDesktopOpenResult, d as PluginUiFileSelectOptions, f as PluginUiFileSelectionItemType, g as PluginUiInitializationPayload, h as PluginUiHostMethods, i as PluginUiCommands, j as WorkbasePluginUi, k as PluginUiView, l as PluginUiExecutionChange, m as PluginUiHostError, n as PluginUiClientMethods, o as PluginUiControllerOptions, p as PluginUiFileSelectionScope, r as PluginUiCommandExecuteOptions, s as PluginUiDesktopOpenOptions, t as PluginDesktopTarget, u as PluginUiFileFilter, v as PluginUiOpenViewOptions, w as PluginUiRepositoryPushResult, x as PluginUiPromptOptions, y as PluginUiOutputOptions } from "../types-CPObI29j.js";
1
+ import { et as DEFAULT_VIEW_STATE_TOPIC, f as PluginCommandExecutionResult } from "../types-DDEHTBRv.js";
2
+ import { A as PluginUiView, C as PluginUiRepositoryPushOutcome, D as PluginUiStatus, E as PluginUiStateChange, M as WorkbasePluginUi, N as WorkbasePluginUiDefinition, O as PluginUiToastOptions, S as PluginUiPromptType, T as PluginUiRepositoryPushTarget, _ as PluginUiNavigateOptions, a as PluginUiContextIdentity, b as PluginUiPromptChoice, c as PluginUiDesktopOpenResult, d as PluginUiFileSelectOptions, f as PluginUiFileSelectionItemType, g as PluginUiInitializationPayload, h as PluginUiHostMethods, i as PluginUiCommands, j as PluginUiViewIdentity, k as PluginUiTransportConnection, l as PluginUiExecutionChange, m as PluginUiHostError, n as PluginUiClientMethods, o as PluginUiControllerOptions, p as PluginUiFileSelectionScope, r as PluginUiCommandExecuteOptions, s as PluginUiDesktopOpenOptions, t as PluginDesktopTarget, u as PluginUiFileFilter, v as PluginUiOpenViewOptions, w as PluginUiRepositoryPushResult, x as PluginUiPromptOptions, y as PluginUiOutputOptions } from "../types-b6G-gae3.js";
2
3
  //#region src/ui/controller.d.ts
3
4
  export declare enum PluginUiHostMethod {
4
5
  InteractionDismiss = "interaction.dismiss",
@@ -25,6 +26,25 @@ export declare enum PluginUiHostMethod {
25
26
  export declare function createPluginUiController(definition: WorkbasePluginUiDefinition, options: PluginUiControllerOptions): WorkbasePluginUi;
26
27
  //#endregion
27
28
  //#region src/ui/index.d.ts
29
+ type ContractEndpoint = (...args: never[]) => unknown;
30
+ type EndpointOutput<Endpoint extends ContractEndpoint> = Awaited<ReturnType<Endpoint>>;
31
+ type CallArgs<Endpoint extends ContractEndpoint> = Parameters<Endpoint>;
32
+ type CommandArgs<Endpoint extends ContractEndpoint> = [] extends Parameters<Endpoint> ? [input?: Parameters<Endpoint>[0], options?: PluginUiCommandExecuteOptions] : [input: Parameters<Endpoint>[0], options?: PluginUiCommandExecuteOptions];
33
+ export interface PluginContract {
34
+ readonly views?: Readonly<Record<string, ContractEndpoint>>;
35
+ readonly commands?: Readonly<Record<string, ContractEndpoint>>;
36
+ readonly statuses?: Readonly<Record<string, ContractEndpoint>>;
37
+ readonly states?: Readonly<Record<string, unknown>>;
38
+ }
39
+ export interface PluginTypedClient<Contract extends PluginContract> {
40
+ readonly host: WorkbasePluginUi;
41
+ readonly view: <Method extends keyof NonNullable<Contract['views']> & string>(method: Method, ...args: CallArgs<NonNullable<Contract['views']>[Method]>) => Promise<EndpointOutput<NonNullable<Contract['views']>[Method]>>;
42
+ readonly command: <CommandId extends keyof NonNullable<Contract['commands']> & string>(commandId: CommandId, ...args: CommandArgs<NonNullable<Contract['commands']>[CommandId]>) => Promise<PluginCommandExecutionResult<EndpointOutput<NonNullable<Contract['commands']>[CommandId]>>>;
43
+ readonly status: <StatusId extends keyof NonNullable<Contract['statuses']> & string>(statusId: StatusId, ...args: CallArgs<NonNullable<Contract['statuses']>[StatusId]>) => Promise<EndpointOutput<NonNullable<Contract['statuses']>[StatusId]>>;
44
+ readonly onState: <Topic extends keyof NonNullable<Contract['states']> & string>(topic: Topic, listener: (state: NonNullable<Contract['states']>[Topic]) => void) => () => void;
45
+ }
46
+ /** Creates an end-to-end typed wrapper over the Workbase plugin UI bridge with zero runtime schema overhead. */
47
+ export declare function createPluginClient<Contract extends PluginContract>(host: WorkbasePluginUi): PluginTypedClient<Contract>;
28
48
  export declare function defineWorkbasePluginUi(definition: WorkbasePluginUiDefinition): WorkbasePluginUi;
29
49
  //#endregion
30
- export { PluginDesktopTarget, type PluginUiClientMethods, type PluginUiCommandExecuteOptions, type PluginUiCommands, type PluginUiContextIdentity, type PluginUiControllerOptions, type PluginUiDesktopOpenOptions, type PluginUiDesktopOpenResult, type PluginUiExecutionChange, type PluginUiFileFilter, type PluginUiFileSelectOptions, type PluginUiFileSelectionItemType, type PluginUiFileSelectionScope, type PluginUiHostError, type PluginUiHostMethods, type PluginUiInitializationPayload, type PluginUiNavigateOptions, type PluginUiOpenViewOptions, type PluginUiOutputOptions, type PluginUiPromptChoice, type PluginUiPromptOptions, type PluginUiPromptType, type PluginUiRepositoryPushOutcome, type PluginUiRepositoryPushResult, type PluginUiRepositoryPushTarget, type PluginUiStatus, type PluginUiToastOptions, type PluginUiTransportConnection, type PluginUiView, type PluginUiViewIdentity, type WorkbasePluginUi, type WorkbasePluginUiDefinition };
50
+ export { DEFAULT_VIEW_STATE_TOPIC, PluginDesktopTarget, type PluginUiClientMethods, type PluginUiCommandExecuteOptions, type PluginUiCommands, type PluginUiContextIdentity, type PluginUiControllerOptions, type PluginUiDesktopOpenOptions, type PluginUiDesktopOpenResult, type PluginUiExecutionChange, type PluginUiFileFilter, type PluginUiFileSelectOptions, type PluginUiFileSelectionItemType, type PluginUiFileSelectionScope, type PluginUiHostError, type PluginUiHostMethods, type PluginUiInitializationPayload, type PluginUiNavigateOptions, type PluginUiOpenViewOptions, type PluginUiOutputOptions, type PluginUiPromptChoice, type PluginUiPromptOptions, type PluginUiPromptType, type PluginUiRepositoryPushOutcome, type PluginUiRepositoryPushResult, type PluginUiRepositoryPushTarget, type PluginUiStateChange, type PluginUiStatus, type PluginUiToastOptions, type PluginUiTransportConnection, type PluginUiView, type PluginUiViewIdentity, type WorkbasePluginUi, type WorkbasePluginUiDefinition };
package/dist/ui/index.js CHANGED
@@ -1,366 +1,3 @@
1
- import { WindowMessenger, connect } from "penpal";
2
- //#region src/ui/controller.ts
3
- const MAX_CONTENT_HEIGHT = 1e4;
4
- const MAX_FATAL_MESSAGE_LENGTH = 1e3;
5
- const MIN_CONTENT_HEIGHT = 1;
6
- let PluginUiHostMethod = /* @__PURE__ */ function(PluginUiHostMethod) {
7
- PluginUiHostMethod["InteractionDismiss"] = "interaction.dismiss";
8
- PluginUiHostMethod["InteractionRespond"] = "interaction.respond";
9
- PluginUiHostMethod["CommandSubscribe"] = "command.subscribe";
10
- PluginUiHostMethod["CommandCancel"] = "command.cancel";
11
- PluginUiHostMethod["CommandStart"] = "command.start";
12
- PluginUiHostMethod["CommandQuery"] = "command.query";
13
- PluginUiHostMethod["CommandReply"] = "command.reply";
14
- PluginUiHostMethod["CommandClear"] = "command.clear";
15
- PluginUiHostMethod["CommandExecute"] = "command.execute";
16
- PluginUiHostMethod["DialogPrompt"] = "dialog.prompt";
17
- PluginUiHostMethod["DesktopOpen"] = "desktop.open";
18
- PluginUiHostMethod["RepositoryAuthorizePush"] = "repository.authorizePush";
19
- PluginUiHostMethod["RepositoryPush"] = "repository.push";
20
- PluginUiHostMethod["FileSelect"] = "file.select";
21
- PluginUiHostMethod["Navigate"] = "navigate";
22
- PluginUiHostMethod["OutputOpen"] = "output.open";
23
- PluginUiHostMethod["StatusResolve"] = "status.resolve";
24
- PluginUiHostMethod["ToastShow"] = "toast.show";
25
- PluginUiHostMethod["ViewCall"] = "view.call";
26
- PluginUiHostMethod["ViewModified"] = "view.modified";
27
- return PluginUiHostMethod;
28
- }({});
29
- function createPluginUiController(definition, options) {
30
- const onInit = definition?.onInit;
31
- const connectToHost = options?.connectToHost;
32
- const targetWindow = options?.targetWindow;
33
- if (typeof onInit !== "function") throw new TypeError("defineWorkbasePluginUi requires an onInit callback.");
34
- if (!targetWindow || typeof connectToHost !== "function") throw new TypeError("Plugin UI transport is unavailable.");
35
- const state = {
36
- fatalReportPromise: null,
37
- isInitialized: false,
38
- isFillLayout: false,
39
- supportsRepositoryPush: false,
40
- supportsRepositoryPushAuthorization: false,
41
- contentHeight: null,
42
- workspaceId: null,
43
- recoverableHostErrors: /* @__PURE__ */ new WeakSet()
44
- };
45
- const executionListeners = /* @__PURE__ */ new Set();
46
- const fileListeners = /* @__PURE__ */ new Set();
47
- let initialization = 0;
48
- let refreshing = false;
49
- let pending = false;
50
- let lifecycle = null;
51
- const clientMethods = {
52
- filesChanged: async () => {
53
- pending = true;
54
- if (refreshing || initialization || !state.isInitialized) return;
55
- refreshing = true;
56
- try {
57
- while (pending) {
58
- pending = false;
59
- await Promise.all([...fileListeners].map((refresh) => refresh()));
60
- }
61
- } finally {
62
- refreshing = false;
63
- }
64
- },
65
- executionChanged: async (change) => {
66
- if (state.isInitialized) [...executionListeners].forEach((listener) => listener(change));
67
- },
68
- initialize: async (payload) => {
69
- assertInitializationPayload(payload);
70
- state.isInitialized = true;
71
- state.isFillLayout = payload.layout === "fill";
72
- state.workspaceId = payload.workspace.id;
73
- state.supportsRepositoryPush = payload.supportsRepositoryPush === true;
74
- state.supportsRepositoryPushAuthorization = payload.supportsRepositoryPushAuthorization === true;
75
- initialization++;
76
- try {
77
- await onInit(payload);
78
- } finally {
79
- initialization--;
80
- }
81
- if (pending) await clientMethods.filesChanged();
82
- if (state.isFillLayout) return;
83
- lifecycle?.observeContentHeight();
84
- await waitForPluginUiPaint(targetWindow);
85
- await reportContentHeight(hostPromise, {
86
- targetWindow,
87
- state
88
- });
89
- }
90
- };
91
- const connection = connectToHost(clientMethods);
92
- const hostPromise = connection.promise;
93
- const request = createHostRequest(hostPromise, state);
94
- lifecycle = bindPluginUiLifecycle({
95
- connection,
96
- state,
97
- targetWindow
98
- });
99
- const dispose = () => {
100
- executionListeners.clear();
101
- fileListeners.clear();
102
- lifecycle?.dispose();
103
- };
104
- const subscribe = async (onChange) => {
105
- const listener = (change) => onChange(change);
106
- executionListeners.add(listener);
107
- try {
108
- await request("command.subscribe", { enabled: true });
109
- } catch (error) {
110
- executionListeners.delete(listener);
111
- throw error;
112
- }
113
- return async () => {
114
- if (!executionListeners.delete(listener) || executionListeners.size) return;
115
- await request("command.subscribe", { enabled: false });
116
- };
117
- };
118
- const onFilesChanged = (refresh) => {
119
- fileListeners.add(refresh);
120
- return () => {
121
- fileListeners.delete(refresh);
122
- };
123
- };
124
- return createPluginUiApi(request, {
125
- targetWindow,
126
- state,
127
- dispose,
128
- subscribe,
129
- onFilesChanged
130
- });
131
- }
132
- function createHostRequest(hostPromise, state) {
133
- return async (method, params) => {
134
- if (!state.isInitialized) throw new Error("插件界面尚未初始化完成。");
135
- if (method === "repository.push" && !state.supportsRepositoryPush || method === "repository.authorizePush" && !state.supportsRepositoryPushAuthorization) {
136
- const error = /* @__PURE__ */ new Error("当前 Workbase 版本无法在插件内推送,请在工作区同步仓库。");
137
- state.recoverableHostErrors.add(error);
138
- throw error;
139
- }
140
- const response = await (await hostPromise).call(method, params);
141
- if (isRecord(response) && response.ok === true) return response.result;
142
- const error = createHostError(response);
143
- state.recoverableHostErrors.add(error);
144
- throw error;
145
- };
146
- }
147
- function createHostError(response) {
148
- const responseError = isRecord(response) && isRecord(response.error) ? response.error : null;
149
- const message = typeof responseError?.message === "string" ? responseError.message : "宿主操作未完成。";
150
- const code = typeof responseError?.code === "string" ? responseError.code : "host_error";
151
- return Object.assign(new Error(message), { code });
152
- }
153
- function createPluginUiApi(request, { targetWindow, state, dispose, subscribe, onFilesChanged }) {
154
- const commands = Object.freeze({
155
- subscribe,
156
- reply: (executionId) => request("command.reply", { executionId }),
157
- clear: (executionId) => request("command.clear", executionId === void 0 ? {} : { executionId }),
158
- start: (commandId, input, options = {}) => request("command.start", {
159
- commandId,
160
- input,
161
- executionId: options.executionId ?? targetWindow.crypto.randomUUID()
162
- }),
163
- query: (executionId) => request("command.query", { executionId: executionId ?? null }),
164
- cancel: (executionId) => request("command.cancel", { executionId }),
165
- execute: (commandId, input, options = {}) => {
166
- return request("command.execute", {
167
- commandId,
168
- executionId: options.executionId ?? targetWindow.crypto.randomUUID(),
169
- input
170
- });
171
- }
172
- });
173
- const status = Object.freeze({ resolve: (statusId, input) => request("status.resolve", {
174
- input,
175
- statusId
176
- }) });
177
- const view = Object.freeze({
178
- onFilesChanged,
179
- setModified: (modified) => request("view.modified", modified),
180
- call: (method, input) => request("view.call", {
181
- input,
182
- method
183
- })
184
- });
185
- const navigate = (to, { replace = false } = {}) => request("navigate", {
186
- replace,
187
- to
188
- });
189
- const openPluginView = async ({ pluginId, viewId, workspaceId, route, params, replace = false }) => {
190
- const resolvedWorkspaceId = workspaceId ?? state.workspaceId;
191
- const search = new URLSearchParams({ viewId });
192
- if (resolvedWorkspaceId) search.set("workspaceId", resolvedWorkspaceId);
193
- if (route) search.set("route", route);
194
- if (params && Object.keys(params).length > 0) search.set("params", JSON.stringify(params));
195
- await navigate(`/plugins/${encodeURIComponent(pluginId)}?${search.toString()}`, { replace });
196
- };
197
- return Object.freeze({
198
- dispose,
199
- dismiss: () => request("interaction.dismiss", {}),
200
- respond: (value) => request("interaction.respond", { value }),
201
- commands,
202
- desktop: Object.freeze({ open: (options) => request("desktop.open", options) }),
203
- repositories: Object.freeze({
204
- authorizePush: (repositoryIds) => request("repository.authorizePush", repositoryIds),
205
- push: (targets, authorizationId) => request("repository.push", authorizationId === void 0 ? targets : {
206
- targets,
207
- authorizationId
208
- })
209
- }),
210
- navigate,
211
- openPluginView,
212
- openOutput: (options) => request("output.open", options),
213
- selectFiles: (options = {}) => request("file.select", options),
214
- showPrompt: (options) => request("dialog.prompt", options),
215
- showToast: (options) => request("toast.show", options),
216
- status,
217
- view
218
- });
219
- }
220
- function bindPluginUiLifecycle({ connection, state, targetWindow }) {
221
- let resizeFrame = null;
222
- let resizeObserver = null;
223
- let isDisposed = false;
224
- const handleWindowError = (event) => {
225
- if (!event.error && (event.message === "ResizeObserver loop completed with undelivered notifications." || event.message === "ResizeObserver loop limit exceeded")) return;
226
- reportFirstFatal(connection.promise, state, event.error ?? event.message);
227
- };
228
- const handleUnhandledRejection = (event) => {
229
- if (event.reason instanceof Error && state.recoverableHostErrors.has(event.reason)) return;
230
- reportFirstFatal(connection.promise, state, event.reason);
231
- };
232
- const startObservingHeight = () => {
233
- if (isDisposed || resizeObserver || state.isFillLayout) return;
234
- resizeObserver = new targetWindow.ResizeObserver(() => {
235
- if (resizeFrame !== null) return;
236
- resizeFrame = targetWindow.requestAnimationFrame(() => {
237
- resizeFrame = null;
238
- if (state.isInitialized && !state.isFillLayout) reportContentHeight(connection.promise, {
239
- targetWindow,
240
- state
241
- });
242
- });
243
- });
244
- resizeObserver.observe(targetWindow.document.body ?? targetWindow.document.documentElement);
245
- };
246
- const cleanup = () => {
247
- if (isDisposed) return;
248
- isDisposed = true;
249
- targetWindow.removeEventListener("error", handleWindowError, true);
250
- targetWindow.removeEventListener("unhandledrejection", handleUnhandledRejection);
251
- targetWindow.removeEventListener("beforeunload", cleanup);
252
- resizeObserver?.disconnect();
253
- resizeObserver = null;
254
- if (resizeFrame !== null) targetWindow.cancelAnimationFrame(resizeFrame);
255
- connection.destroy();
256
- state.fatalReportPromise = null;
257
- state.isInitialized = false;
258
- };
259
- ignoreConnectionFailure(connection.promise);
260
- targetWindow.addEventListener("error", handleWindowError, true);
261
- targetWindow.addEventListener("unhandledrejection", handleUnhandledRejection);
262
- targetWindow.addEventListener("beforeunload", cleanup, { once: true });
263
- return {
264
- observeContentHeight: startObservingHeight,
265
- dispose: cleanup
266
- };
267
- }
268
- async function ignoreConnectionFailure(hostPromise) {
269
- try {
270
- await hostPromise;
271
- } catch {}
272
- }
273
- async function waitForPluginUiPaint(targetWindow) {
274
- await new Promise((resolve) => {
275
- targetWindow.requestAnimationFrame(() => {
276
- targetWindow.requestAnimationFrame(() => resolve());
277
- });
278
- });
279
- }
280
- async function reportFirstFatal(hostPromise, state, error) {
281
- if (!state.fatalReportPromise) state.fatalReportPromise = sendFatalReport(hostPromise, getFatalMessage(error).slice(0, MAX_FATAL_MESSAGE_LENGTH));
282
- await state.fatalReportPromise;
283
- }
284
- async function sendFatalReport(hostPromise, message) {
285
- try {
286
- await (await hostPromise).reportFatal(message);
287
- } catch {}
288
- }
289
- async function reportContentHeight(hostPromise, { targetWindow, state }) {
290
- const contentElement = targetWindow.document.body ?? targetWindow.document.documentElement;
291
- const height = Math.max(contentElement.offsetHeight, contentElement.scrollHeight);
292
- if (!Number.isFinite(height)) return;
293
- try {
294
- const host = await hostPromise;
295
- const contentHeight = Math.min(Math.max(Math.ceil(height), MIN_CONTENT_HEIGHT), MAX_CONTENT_HEIGHT);
296
- if (!state.isInitialized || state.contentHeight === contentHeight) return;
297
- state.contentHeight = contentHeight;
298
- await host.reportContentHeight(contentHeight);
299
- } catch {}
300
- }
301
- function assertInitializationPayload(value) {
302
- if (!isInitializationPayload(value)) throw new TypeError("插件界面初始化参数无效。");
303
- }
304
- function isInitializationPayload(value) {
305
- if (!isRecord(value)) return false;
306
- if (value.configurationRevision !== void 0 && typeof value.configurationRevision !== "string") return false;
307
- if (value.activationGeneration !== void 0 && (!Number.isSafeInteger(value.activationGeneration) || Number(value.activationGeneration) < 0)) return false;
308
- return isContextIdentity(value.project) && isContextIdentity(value.workspace) && isViewIdentity(value.view);
309
- }
310
- function isContextIdentity(value) {
311
- return isRecord(value) && typeof value.id === "string" && value.id.length > 0;
312
- }
313
- function isViewIdentity(value) {
314
- return isContextIdentity(value) && isRecord(value) && typeof value.pluginId === "string" && value.pluginId.length > 0 && typeof value.title === "string" && value.title.length > 0;
315
- }
316
- function isRecord(value) {
317
- return value !== null && typeof value === "object" && !Array.isArray(value);
318
- }
319
- function getFatalMessage(error) {
320
- if (error instanceof Error) return error.message;
321
- if (typeof error === "string" && error.trim().length > 0) return error;
322
- return "插件界面遇到异常。";
323
- }
324
- //#endregion
325
- //#region src/ui/types.ts
326
- let PluginDesktopTarget = /* @__PURE__ */ function(PluginDesktopTarget) {
327
- PluginDesktopTarget["Editor"] = "editor";
328
- PluginDesktopTarget["Terminal"] = "terminal";
329
- PluginDesktopTarget["Folder"] = "folder";
330
- PluginDesktopTarget["Chatgpt"] = "chatgpt";
331
- return PluginDesktopTarget;
332
- }({});
333
- //#endregion
334
- //#region src/ui/index.ts
335
- /**
336
- * Penpal browser entry for trusted Workbase plugin views.
337
- */
338
- const BRIDGE_CHANNEL = "workbase-plugin-ui-v1";
339
- const HOST_ORIGIN_PARAMETER = "__workbaseHostOrigin";
340
- function defineWorkbasePluginUi(definition) {
341
- const targetWindow = window;
342
- return createPluginUiController(definition, {
343
- connectToHost: (methods) => createPenpalConnection(targetWindow, methods),
344
- targetWindow
345
- });
346
- }
347
- function createPenpalConnection(targetWindow, methods) {
348
- const connection = connect({
349
- channel: BRIDGE_CHANNEL,
350
- messenger: new WindowMessenger({
351
- allowedOrigins: resolveParentOrigins(targetWindow),
352
- remoteWindow: targetWindow.parent
353
- }),
354
- methods
355
- });
356
- return {
357
- destroy: connection.destroy,
358
- promise: connection.promise
359
- };
360
- }
361
- function resolveParentOrigins(targetWindow) {
362
- const hostOrigin = new URL(targetWindow.location.href).searchParams.get(HOST_ORIGIN_PARAMETER);
363
- return hostOrigin && hostOrigin !== "null" ? [hostOrigin] : ["*"];
364
- }
365
- //#endregion
366
- export { PluginDesktopTarget, PluginUiHostMethod, createPluginUiController, defineWorkbasePluginUi };
1
+ import { t as DEFAULT_VIEW_STATE_TOPIC } from "../host-services-cIH3aYQD.js";
2
+ import { a as createPluginUiController, i as PluginUiHostMethod, n as defineWorkbasePluginUi, r as PluginDesktopTarget, t as createPluginClient } from "../ui-DGLeDJDe.js";
3
+ export { DEFAULT_VIEW_STATE_TOPIC, PluginDesktopTarget, PluginUiHostMethod, createPluginClient, createPluginUiController, defineWorkbasePluginUi };
@@ -1,4 +1,4 @@
1
- import { j as WorkbasePluginUi } from "../types-CPObI29j.js";
1
+ import { M as WorkbasePluginUi } from "../types-b6G-gae3.js";
2
2
  import { ReactNode } from "react";
3
3
  //#region src/ui/MarkdownLinks.dto.d.ts
4
4
  interface MarkdownLinksProps {
@@ -1,4 +1,4 @@
1
- import { D as PluginUiToastOptions, j as WorkbasePluginUi } from "../types-CPObI29j.js";
1
+ import { M as WorkbasePluginUi, O as PluginUiToastOptions } from "../types-b6G-gae3.js";
2
2
  //#region src/ui/model.d.ts
3
3
  /** A notification transport failure must not turn a completed operation into a failed one. */
4
4
  export declare function showOperationToast(host: Pick<WorkbasePluginUi, "showToast">, options: PluginUiToastOptions): void;