@eworkbase/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Public authoring entry for trusted Workbase plugins.
3
+ */
4
+ export * from "zod";
5
+ export { definePlugin, isDefinedPlugin } from "./definition.js";
6
+ export type { DefinedWorkbasePlugin } from "./definition.js";
7
+ export { PluginCommandCategory, PluginCommandEffect, PluginCommandExecutionMode, PluginCommandTransaction, PluginHookId, PluginLifecyclePolicy, PluginLifecycleStatus, PluginRepositoryStatus, PluginViewLayout, } from "./types.js";
8
+ export type { PluginAgentContextCatalogEntry, PluginAgentContextContribution, PluginAgentContextDefinition, PluginAgentPolicy, PluginCapabilityCatalog, PluginCapabilityCommandRequest, PluginCapabilityResolveRequest, PluginCapabilityService, PluginColoredMessage, PluginCommandArgument, PluginCommandCatalogEntry, PluginCommandContext, PluginCommandContribution, PluginCommandDefinition, PluginCommandOption, PluginConfigApi, PluginContext, PluginContributionSnapshot, PluginDisposable, PluginHookResult, PluginHostServices, PluginInteractiveLogger, PluginInvocationContext, PluginLifecycleDispatchResult, PluginLifecycleHook, PluginLifecycleOutcome, PluginLogEntry, PluginLogQueryRequest, PluginLogQueryResult, PluginLogService, PluginLogger, PluginProcessApi, PluginProcessResult, PluginProcessRunOptions, PluginProject, PluginRepository, PluginPromptApi, PluginPromptChoice, PluginPromptQuestion, PluginPromptType, PluginSetupHooks, PluginStatusContribution, PluginStatusCatalogEntry, PluginStatusDefinition, PluginStoreApi, PluginSystemContextService, PluginTaskDescriptor, PluginTaskResult, PluginTaskService, PluginToastApi, PluginToastLevel, PluginToastOptions, PluginToolContribution, PluginViewContribution, PluginViewCatalogEntry, PluginViewDefinition, PluginViewRequest, PluginWorkspace, WorkbasePluginDefinition, } from "./types.js";
package/index.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Public authoring entry for trusted Workbase plugins.
3
+ */
4
+ export * from "zod";
5
+ // ─── Definition ────────────────────────────────────────────────────────
6
+ export { definePlugin, isDefinedPlugin } from "./definition.js";
7
+ // ─── Runtime Values ─────────────────────────────────────────────
8
+ export { PluginCommandCategory, PluginCommandEffect, PluginCommandExecutionMode, PluginCommandTransaction, PluginHookId, PluginLifecyclePolicy, PluginLifecycleStatus, PluginRepositoryStatus, PluginViewLayout, } from "./types.js";
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@eworkbase/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Typed backend and browser APIs for independently developed Workbase plugins.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./index.d.ts",
9
+ "import": "./index.js"
10
+ },
11
+ "./ui": {
12
+ "types": "./ui/index.d.ts",
13
+ "import": "./ui/index.js"
14
+ },
15
+ "./ui/index.css": "./ui/index.css",
16
+ "./ui/model": {
17
+ "types": "./ui/model.d.ts",
18
+ "import": "./ui/model.js"
19
+ }
20
+ },
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "dependencies": {
25
+ "penpal": "^7.0.0",
26
+ "zod": "^4.3.6"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ }
31
+ }
package/types.d.ts ADDED
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Canonical plugin definitions and host-shared runtime contracts.
3
+ */
4
+ import type { ZodType } from "zod";
5
+ import type { PluginHostServices } from "./host-services.js";
6
+ export type { PluginAgentContextCatalogEntry, PluginAgentPolicy, PluginCapabilityCatalog, PluginCapabilityCommandRequest, PluginCapabilityResolveRequest, PluginCapabilityService, PluginColoredMessage, PluginCommandCatalogEntry, PluginConfigApi, PluginHostServices, PluginInteractiveLogger, PluginLogEntry, PluginLogQueryRequest, PluginLogQueryResult, PluginLogService, PluginPromptApi, PluginPromptChoice, PluginPromptQuestion, PluginPromptType, PluginStoreApi, PluginStatusCatalogEntry, PluginSystemContextService, PluginTaskDescriptor, PluginTaskResult, PluginTaskService, PluginToastApi, PluginToastLevel, PluginToastOptions, PluginViewCatalogEntry, } from "./host-services.js";
7
+ export declare enum PluginHookId {
8
+ ProjectReconcile = "project.reconcile",
9
+ WorkspaceActivate = "workspace.activate",
10
+ WorkspaceAfterPrepare = "workspace.afterPrepare",
11
+ WorkspaceDeactivate = "workspace.deactivate",
12
+ WorkspaceProvision = "workspace.provision",
13
+ Cleanup = "cleanup"
14
+ }
15
+ export declare enum PluginCommandEffect {
16
+ Immediate = "immediate",
17
+ LongRunning = "longRunning"
18
+ }
19
+ export declare enum PluginCommandTransaction {
20
+ None = "none",
21
+ ProjectMutation = "projectMutation"
22
+ }
23
+ export declare enum PluginCommandCategory {
24
+ Build = "build",
25
+ Publish = "publish",
26
+ Run = "run",
27
+ Settings = "settings"
28
+ }
29
+ export declare enum PluginCommandExecutionMode {
30
+ Async = "async",
31
+ Persistent = "persistent",
32
+ Sync = "sync"
33
+ }
34
+ export declare enum PluginLifecyclePolicy {
35
+ BestEffort = "bestEffort",
36
+ FailFast = "failFast"
37
+ }
38
+ export declare enum PluginLifecycleStatus {
39
+ Failed = "failed",
40
+ Succeeded = "succeeded"
41
+ }
42
+ export declare enum PluginRepositoryStatus {
43
+ NotPrepared = "not-prepared",
44
+ Ready = "ready"
45
+ }
46
+ export declare enum PluginViewLayout {
47
+ Content = "content",
48
+ Fill = "fill"
49
+ }
50
+ export interface PluginDisposable {
51
+ readonly dispose: () => void;
52
+ }
53
+ export interface PluginProject {
54
+ readonly id: string;
55
+ readonly root: string;
56
+ readonly workbaseRoot: string;
57
+ }
58
+ export interface PluginRepository {
59
+ readonly baseBranch: string;
60
+ readonly branch: string;
61
+ readonly id: string;
62
+ readonly label: string;
63
+ readonly root: string;
64
+ readonly status: PluginRepositoryStatus;
65
+ }
66
+ export interface PluginWorkspace {
67
+ readonly id: string;
68
+ readonly repositories: readonly PluginRepository[];
69
+ readonly root: string;
70
+ }
71
+ export interface PluginLogger {
72
+ readonly debug: (...values: readonly unknown[]) => void;
73
+ readonly error: (...values: readonly unknown[]) => void;
74
+ readonly info: (...values: readonly unknown[]) => void;
75
+ readonly warn: (...values: readonly unknown[]) => void;
76
+ }
77
+ export interface PluginProcessRunOptions {
78
+ readonly program: string;
79
+ readonly arguments?: readonly string[];
80
+ readonly currentDirectory?: string;
81
+ readonly environment?: Readonly<Record<string, string | undefined>>;
82
+ readonly timeoutMilliseconds?: number;
83
+ }
84
+ export interface PluginProcessResult {
85
+ readonly command: string;
86
+ readonly errorMessage: string | null;
87
+ readonly exitCode: number | null;
88
+ readonly failed: boolean;
89
+ readonly standardError: string;
90
+ readonly standardOutput: string;
91
+ readonly timedOut: boolean;
92
+ readonly wasCancelled: boolean;
93
+ }
94
+ export interface PluginProcessApi {
95
+ readonly run: (options: PluginProcessRunOptions, signal?: AbortSignal) => Promise<PluginProcessResult>;
96
+ }
97
+ export interface PluginContext {
98
+ readonly config: Readonly<Record<string, unknown>>;
99
+ readonly logger: PluginLogger;
100
+ readonly pluginId: string;
101
+ readonly process: PluginProcessApi;
102
+ readonly project: PluginProject;
103
+ readonly services: PluginHostServices;
104
+ readonly workspace: PluginWorkspace;
105
+ }
106
+ export interface PluginInvocationContext {
107
+ readonly process: PluginProcessApi;
108
+ readonly services: PluginHostServices;
109
+ readonly signal: AbortSignal;
110
+ }
111
+ export interface PluginCommandContext extends PluginInvocationContext {
112
+ readonly executionId: string;
113
+ }
114
+ export interface PluginCommandDefinition {
115
+ readonly agent?: import("./host-services.js").PluginAgentPolicy;
116
+ readonly arguments?: readonly PluginCommandArgument[];
117
+ readonly category?: PluginCommandCategory;
118
+ readonly description?: string;
119
+ readonly effect?: PluginCommandEffect;
120
+ readonly executionMode?: PluginCommandExecutionMode | ((input: Readonly<Record<string, unknown>>) => PluginCommandExecutionMode);
121
+ readonly id: string;
122
+ readonly input?: ZodType;
123
+ readonly options?: readonly PluginCommandOption[];
124
+ readonly run: (input: unknown, context: PluginCommandContext) => unknown | Promise<unknown>;
125
+ readonly title: string;
126
+ readonly transaction?: PluginCommandTransaction;
127
+ }
128
+ export interface PluginCommandArgument {
129
+ readonly description: string;
130
+ readonly name: string;
131
+ readonly required?: boolean;
132
+ }
133
+ export interface PluginCommandOption {
134
+ readonly default?: unknown;
135
+ readonly description: string;
136
+ readonly flags: string;
137
+ }
138
+ export interface PluginAgentContextDefinition {
139
+ readonly description: string;
140
+ readonly id: string;
141
+ readonly title: string;
142
+ readonly resolve: (input: unknown, context: PluginInvocationContext) => unknown | Promise<unknown>;
143
+ }
144
+ export interface PluginViewRequest {
145
+ readonly input: unknown;
146
+ readonly method: string;
147
+ }
148
+ export interface PluginViewDefinition {
149
+ readonly description?: string;
150
+ readonly entry: string;
151
+ readonly handlers?: Readonly<Record<string, (input: unknown, context: PluginInvocationContext) => unknown | Promise<unknown>>>;
152
+ readonly id: string;
153
+ readonly layout?: PluginViewLayout;
154
+ readonly order?: number;
155
+ readonly request?: (request: PluginViewRequest, context: PluginInvocationContext) => unknown | Promise<unknown>;
156
+ readonly slot: string;
157
+ readonly title?: string;
158
+ }
159
+ export interface PluginStatusDefinition {
160
+ readonly description: string;
161
+ readonly id: string;
162
+ readonly label: string;
163
+ readonly resolve: (input: unknown, context: PluginInvocationContext) => unknown | Promise<unknown>;
164
+ }
165
+ export interface PluginToolContribution {
166
+ readonly id: string;
167
+ readonly pluginId: string;
168
+ readonly version?: string;
169
+ }
170
+ export interface PluginLifecycleOutcome {
171
+ readonly code: string | null;
172
+ readonly details: unknown | null;
173
+ readonly durationMilliseconds: number;
174
+ readonly error: string | null;
175
+ readonly pluginId: string;
176
+ readonly retryable: boolean;
177
+ readonly standardError: string;
178
+ readonly standardOutput: string;
179
+ readonly status: PluginLifecycleStatus;
180
+ readonly tap: string;
181
+ readonly warnings: readonly string[];
182
+ }
183
+ export interface PluginHookResult {
184
+ readonly standardError?: string;
185
+ readonly standardOutput?: string;
186
+ readonly warnings?: readonly string[];
187
+ }
188
+ export interface PluginLifecycleDispatchResult {
189
+ readonly hookId: PluginHookId;
190
+ readonly outcomes: readonly PluginLifecycleOutcome[];
191
+ readonly policy: PluginLifecyclePolicy;
192
+ }
193
+ export interface PluginLifecycleHook {
194
+ readonly tap: (name: string, handler: (payload: unknown, context: PluginInvocationContext) => void | PluginHookResult | Promise<void | PluginHookResult>) => void;
195
+ }
196
+ export interface PluginSetupHooks {
197
+ readonly onCleanup: PluginLifecycleHook;
198
+ readonly onProjectReconcile: PluginLifecycleHook;
199
+ readonly onWorkspaceActivate: PluginLifecycleHook;
200
+ readonly onWorkspaceAfterPrepare: PluginLifecycleHook;
201
+ readonly onWorkspaceDeactivate: PluginLifecycleHook;
202
+ readonly onWorkspaceProvision: PluginLifecycleHook;
203
+ readonly registerAgentContext: (definition: PluginAgentContextDefinition) => void;
204
+ readonly registerCommand: (definition: PluginCommandDefinition) => void;
205
+ readonly registerStatus: (definition: PluginStatusDefinition) => void;
206
+ readonly registerView: (definition: PluginViewDefinition) => void;
207
+ }
208
+ export interface WorkbasePluginDefinition {
209
+ readonly dependencies?: readonly string[];
210
+ readonly id: string;
211
+ readonly setup: (context: PluginContext, hooks: PluginSetupHooks) => void | Promise<void>;
212
+ readonly title: string;
213
+ }
214
+ export interface PluginCommandContribution {
215
+ readonly description?: string;
216
+ readonly effect: PluginCommandEffect;
217
+ readonly id: string;
218
+ readonly pluginId: string;
219
+ readonly title: string;
220
+ readonly transaction: PluginCommandTransaction;
221
+ }
222
+ export interface PluginAgentContextContribution {
223
+ readonly id: string;
224
+ readonly pluginId: string;
225
+ }
226
+ export interface PluginViewContribution {
227
+ readonly entry: string;
228
+ readonly id: string;
229
+ readonly layout: PluginViewLayout;
230
+ readonly order: number;
231
+ readonly pluginId: string;
232
+ readonly slot: string;
233
+ readonly title: string;
234
+ }
235
+ export interface PluginStatusContribution {
236
+ readonly id: string;
237
+ readonly label: string;
238
+ readonly pluginId: string;
239
+ }
240
+ export interface PluginContributionSnapshot {
241
+ readonly agentContexts: readonly PluginAgentContextContribution[];
242
+ readonly commands: readonly PluginCommandContribution[];
243
+ readonly statuses: readonly PluginStatusContribution[];
244
+ readonly tools: readonly PluginToolContribution[];
245
+ readonly views: readonly PluginViewContribution[];
246
+ }
package/types.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Canonical plugin definitions and host-shared runtime contracts.
3
+ */
4
+ // ─── Shared Enums ───────────────────────────────────────────────
5
+ export var PluginHookId;
6
+ (function (PluginHookId) {
7
+ PluginHookId["ProjectReconcile"] = "project.reconcile";
8
+ PluginHookId["WorkspaceActivate"] = "workspace.activate";
9
+ PluginHookId["WorkspaceAfterPrepare"] = "workspace.afterPrepare";
10
+ PluginHookId["WorkspaceDeactivate"] = "workspace.deactivate";
11
+ PluginHookId["WorkspaceProvision"] = "workspace.provision";
12
+ PluginHookId["Cleanup"] = "cleanup";
13
+ })(PluginHookId || (PluginHookId = {}));
14
+ export var PluginCommandEffect;
15
+ (function (PluginCommandEffect) {
16
+ PluginCommandEffect["Immediate"] = "immediate";
17
+ PluginCommandEffect["LongRunning"] = "longRunning";
18
+ })(PluginCommandEffect || (PluginCommandEffect = {}));
19
+ export var PluginCommandTransaction;
20
+ (function (PluginCommandTransaction) {
21
+ PluginCommandTransaction["None"] = "none";
22
+ PluginCommandTransaction["ProjectMutation"] = "projectMutation";
23
+ })(PluginCommandTransaction || (PluginCommandTransaction = {}));
24
+ export var PluginCommandCategory;
25
+ (function (PluginCommandCategory) {
26
+ PluginCommandCategory["Build"] = "build";
27
+ PluginCommandCategory["Publish"] = "publish";
28
+ PluginCommandCategory["Run"] = "run";
29
+ PluginCommandCategory["Settings"] = "settings";
30
+ })(PluginCommandCategory || (PluginCommandCategory = {}));
31
+ export var PluginCommandExecutionMode;
32
+ (function (PluginCommandExecutionMode) {
33
+ PluginCommandExecutionMode["Async"] = "async";
34
+ PluginCommandExecutionMode["Persistent"] = "persistent";
35
+ PluginCommandExecutionMode["Sync"] = "sync";
36
+ })(PluginCommandExecutionMode || (PluginCommandExecutionMode = {}));
37
+ export var PluginLifecyclePolicy;
38
+ (function (PluginLifecyclePolicy) {
39
+ PluginLifecyclePolicy["BestEffort"] = "bestEffort";
40
+ PluginLifecyclePolicy["FailFast"] = "failFast";
41
+ })(PluginLifecyclePolicy || (PluginLifecyclePolicy = {}));
42
+ export var PluginLifecycleStatus;
43
+ (function (PluginLifecycleStatus) {
44
+ PluginLifecycleStatus["Failed"] = "failed";
45
+ PluginLifecycleStatus["Succeeded"] = "succeeded";
46
+ })(PluginLifecycleStatus || (PluginLifecycleStatus = {}));
47
+ export var PluginRepositoryStatus;
48
+ (function (PluginRepositoryStatus) {
49
+ PluginRepositoryStatus["NotPrepared"] = "not-prepared";
50
+ PluginRepositoryStatus["Ready"] = "ready";
51
+ })(PluginRepositoryStatus || (PluginRepositoryStatus = {}));
52
+ export var PluginViewLayout;
53
+ (function (PluginViewLayout) {
54
+ PluginViewLayout["Content"] = "content";
55
+ PluginViewLayout["Fill"] = "fill";
56
+ })(PluginViewLayout || (PluginViewLayout = {}));
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Browser-agnostic controller for the Workbase plugin view API.
3
+ */
4
+ import type { PluginUiControllerOptions, WorkbasePluginUi, WorkbasePluginUiDefinition } from './types.js';
5
+ export declare function createPluginUiController(definition: WorkbasePluginUiDefinition, options: PluginUiControllerOptions): WorkbasePluginUi;
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Browser-agnostic controller for the Workbase plugin view API.
3
+ */
4
+ const MAX_CONTENT_HEIGHT = 10_000;
5
+ const MAX_FATAL_MESSAGE_LENGTH = 1_000;
6
+ const MIN_CONTENT_HEIGHT = 1;
7
+ // ─── Types ───────────────────────────────────────────────────
8
+ var PluginUiHostMethod;
9
+ (function (PluginUiHostMethod) {
10
+ PluginUiHostMethod["CommandCancel"] = "command.cancel";
11
+ PluginUiHostMethod["CommandExecute"] = "command.execute";
12
+ PluginUiHostMethod["DialogPrompt"] = "dialog.prompt";
13
+ PluginUiHostMethod["FileSelect"] = "file.select";
14
+ PluginUiHostMethod["Navigate"] = "navigate";
15
+ PluginUiHostMethod["OutputClose"] = "output.close";
16
+ PluginUiHostMethod["OutputOpen"] = "output.open";
17
+ PluginUiHostMethod["OutputUpdate"] = "output.update";
18
+ PluginUiHostMethod["StatusResolve"] = "status.resolve";
19
+ PluginUiHostMethod["ToastShow"] = "toast.show";
20
+ PluginUiHostMethod["ViewCall"] = "view.call";
21
+ })(PluginUiHostMethod || (PluginUiHostMethod = {}));
22
+ // ─── Public API ──────────────────────────────────────────────
23
+ export function createPluginUiController(definition, options) {
24
+ const onInit = definition?.onInit;
25
+ const connectToHost = options?.connectToHost;
26
+ const targetWindow = options?.targetWindow;
27
+ if (typeof onInit !== 'function') {
28
+ throw new TypeError('defineWorkbasePluginUi requires an onInit callback.');
29
+ }
30
+ if (!targetWindow || typeof connectToHost !== 'function') {
31
+ throw new TypeError('Plugin UI transport is unavailable.');
32
+ }
33
+ const state = {
34
+ fatalReportPromise: null,
35
+ isInitialized: false,
36
+ recoverableHostErrors: new WeakSet(),
37
+ };
38
+ const clientMethods = {
39
+ initialize: async (payload) => {
40
+ assertInitializationPayload(payload);
41
+ state.isInitialized = true;
42
+ await onInit(payload);
43
+ await waitForPluginUiPaint(targetWindow);
44
+ await reportContentHeight(hostPromise, targetWindow);
45
+ },
46
+ };
47
+ const connection = connectToHost(clientMethods);
48
+ const hostPromise = connection.promise;
49
+ const request = createHostRequest(hostPromise, state);
50
+ bindPluginUiLifecycle({ connection, state, targetWindow });
51
+ return createPluginUiApi(request, targetWindow);
52
+ }
53
+ // ─── Host Requests ───────────────────────────────────────────
54
+ function createHostRequest(hostPromise, state) {
55
+ return async (method, params) => {
56
+ if (!state.isInitialized) {
57
+ throw new Error('Plugin UI is not initialized.');
58
+ }
59
+ const host = await hostPromise;
60
+ const response = await host.call(method, params);
61
+ if (isRecord(response) && response.ok === true) {
62
+ return response.result;
63
+ }
64
+ const error = createHostError(response);
65
+ state.recoverableHostErrors.add(error);
66
+ throw error;
67
+ };
68
+ }
69
+ function createHostError(response) {
70
+ const responseError = isRecord(response) && isRecord(response.error) ? response.error : null;
71
+ const message = typeof responseError?.message === 'string' ? responseError.message : 'Host action failed.';
72
+ const code = typeof responseError?.code === 'string' ? responseError.code : 'host_error';
73
+ return Object.assign(new Error(message), { code });
74
+ }
75
+ // ─── API Mapping ─────────────────────────────────────────────
76
+ function createPluginUiApi(request, targetWindow) {
77
+ const commands = Object.freeze({
78
+ cancel: (executionId) => request(PluginUiHostMethod.CommandCancel, { executionId }),
79
+ execute: (commandId, input, options = {}) => {
80
+ const executionId = options.executionId ?? targetWindow.crypto.randomUUID();
81
+ return request(PluginUiHostMethod.CommandExecute, { commandId, executionId, input });
82
+ },
83
+ });
84
+ const status = Object.freeze({
85
+ resolve: (statusId, input) => request(PluginUiHostMethod.StatusResolve, { input, statusId }),
86
+ });
87
+ const view = Object.freeze({
88
+ call: (method, input) => request(PluginUiHostMethod.ViewCall, { input, method }),
89
+ });
90
+ return Object.freeze({
91
+ closeOutput: (id) => request(PluginUiHostMethod.OutputClose, { id }),
92
+ commands,
93
+ navigate: (to, { replace = false } = {}) => request(PluginUiHostMethod.Navigate, { replace, to }),
94
+ openOutput: (options) => request(PluginUiHostMethod.OutputOpen, options),
95
+ selectFiles: (options = {}) => request(PluginUiHostMethod.FileSelect, options),
96
+ showPrompt: (options) => request(PluginUiHostMethod.DialogPrompt, options),
97
+ showToast: (options) => request(PluginUiHostMethod.ToastShow, options),
98
+ status,
99
+ updateOutput: (options) => request(PluginUiHostMethod.OutputUpdate, options),
100
+ view,
101
+ });
102
+ }
103
+ // ─── Window Lifecycle ────────────────────────────────────────
104
+ function bindPluginUiLifecycle({ connection, state, targetWindow }) {
105
+ const handleWindowError = (event) => {
106
+ void reportFirstFatal(connection.promise, state, event.error ?? event.message);
107
+ };
108
+ const handleUnhandledRejection = (event) => {
109
+ if (event.reason instanceof Error && state.recoverableHostErrors.has(event.reason)) {
110
+ return;
111
+ }
112
+ void reportFirstFatal(connection.promise, state, event.reason);
113
+ };
114
+ const resizeObserver = new targetWindow.ResizeObserver(() => {
115
+ void reportContentHeight(connection.promise, targetWindow);
116
+ });
117
+ const cleanup = () => {
118
+ targetWindow.removeEventListener('error', handleWindowError, true);
119
+ targetWindow.removeEventListener('unhandledrejection', handleUnhandledRejection);
120
+ targetWindow.removeEventListener('beforeunload', cleanup);
121
+ resizeObserver.disconnect();
122
+ connection.destroy();
123
+ state.fatalReportPromise = null;
124
+ state.isInitialized = false;
125
+ };
126
+ void ignoreConnectionFailure(connection.promise);
127
+ resizeObserver.observe(targetWindow.document.body ?? targetWindow.document.documentElement);
128
+ targetWindow.addEventListener('error', handleWindowError, true);
129
+ targetWindow.addEventListener('unhandledrejection', handleUnhandledRejection);
130
+ targetWindow.addEventListener('beforeunload', cleanup, { once: true });
131
+ }
132
+ async function ignoreConnectionFailure(hostPromise) {
133
+ try {
134
+ await hostPromise;
135
+ }
136
+ catch {
137
+ // The parent owns connection timeout and fallback UI.
138
+ }
139
+ }
140
+ async function waitForPluginUiPaint(targetWindow) {
141
+ await new Promise((resolve) => {
142
+ targetWindow.requestAnimationFrame(() => {
143
+ targetWindow.requestAnimationFrame(() => resolve());
144
+ });
145
+ });
146
+ }
147
+ async function reportFirstFatal(hostPromise, state, error) {
148
+ if (!state.fatalReportPromise) {
149
+ const fatalMessage = getFatalMessage(error).slice(0, MAX_FATAL_MESSAGE_LENGTH);
150
+ state.fatalReportPromise = sendFatalReport(hostPromise, fatalMessage);
151
+ }
152
+ await state.fatalReportPromise;
153
+ }
154
+ async function sendFatalReport(hostPromise, message) {
155
+ try {
156
+ const host = await hostPromise;
157
+ await host.reportFatal(message);
158
+ }
159
+ catch {
160
+ // The parent reports connection failures and owns fallback selection.
161
+ }
162
+ }
163
+ async function reportContentHeight(hostPromise, targetWindow) {
164
+ const contentElement = targetWindow.document.body ?? targetWindow.document.documentElement;
165
+ const height = Math.max(contentElement.offsetHeight, contentElement.scrollHeight);
166
+ if (!Number.isFinite(height)) {
167
+ return;
168
+ }
169
+ try {
170
+ const host = await hostPromise;
171
+ const contentHeight = Math.min(Math.max(Math.ceil(height), MIN_CONTENT_HEIGHT), MAX_CONTENT_HEIGHT);
172
+ await host.reportContentHeight(contentHeight);
173
+ }
174
+ catch {
175
+ // The frame may unload while a resize notification is pending.
176
+ }
177
+ }
178
+ // ─── Validation ──────────────────────────────────────────────
179
+ function assertInitializationPayload(value) {
180
+ if (!isInitializationPayload(value)) {
181
+ throw new TypeError('Plugin UI initialization payload is invalid.');
182
+ }
183
+ }
184
+ function isInitializationPayload(value) {
185
+ if (!isRecord(value)) {
186
+ return false;
187
+ }
188
+ return isContextIdentity(value.project) && isContextIdentity(value.workspace) && isViewIdentity(value.view);
189
+ }
190
+ function isContextIdentity(value) {
191
+ return isRecord(value) && typeof value.id === 'string' && value.id.length > 0;
192
+ }
193
+ function isViewIdentity(value) {
194
+ return (isContextIdentity(value) &&
195
+ isRecord(value) &&
196
+ typeof value.pluginId === 'string' &&
197
+ value.pluginId.length > 0 &&
198
+ typeof value.title === 'string' &&
199
+ value.title.length > 0);
200
+ }
201
+ function isRecord(value) {
202
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
203
+ }
204
+ function getFatalMessage(error) {
205
+ if (error instanceof Error) {
206
+ return error.message;
207
+ }
208
+ if (typeof error === 'string' && error.trim().length > 0) {
209
+ return error;
210
+ }
211
+ return 'Plugin UI failed.';
212
+ }