bunite-core 0.16.0 → 0.17.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/package.json +4 -4
- package/src/host/core/App.ts +4 -2
- package/src/host/core/BrowserWindow.ts +52 -6
- package/src/host/core/windowCap.ts +69 -0
- package/src/host/native.ts +6 -1
- package/src/native/linux/bunite_linux_ffi.cpp +20 -0
- package/src/native/linux/bunite_linux_runtime.cpp +1 -1
- package/src/native/mac/bunite_mac_ffi.mm +16 -1
- package/src/native/shared/ffi_exports.h +4 -0
- package/src/native/win/native_host_cef.cpp +5 -3
- package/src/native/win/native_host_ffi.cpp +14 -1
- package/src/native/win/native_host_runtime.cpp +34 -0
- package/src/native/win-webview2/bunite_webview2_ffi.cpp +40 -2
- package/src/native/win-webview2/webview2_internal.h +5 -0
- package/src/native/win-webview2/webview2_runtime.cpp +107 -8
- package/src/preload/runtime.built.js +1 -1
- package/src/preload/runtime.ts +39 -0
- package/src/rpc/framework.ts +20 -1
- package/src/rpc/index.ts +1 -0
- package/src/rpc/peer.ts +1 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bunite-core",
|
|
3
3
|
"description": "Uniting UI and Bun",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.17.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"setup:cef": "bun ../tools/bunite-dev/scripts/setup-cef.ts",
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
"msgpackr": "^1.11.9"
|
|
25
25
|
},
|
|
26
26
|
"optionalDependencies": {
|
|
27
|
-
"bunite-native-win-x64": "0.0.
|
|
28
|
-
"bunite-native-mac-arm64": "0.0.
|
|
29
|
-
"bunite-native-linux-x64": "0.0.
|
|
27
|
+
"bunite-native-win-x64": "0.0.15",
|
|
28
|
+
"bunite-native-mac-arm64": "0.0.5",
|
|
29
|
+
"bunite-native-linux-x64": "0.0.5"
|
|
30
30
|
}
|
|
31
31
|
}
|
package/src/host/core/App.ts
CHANGED
|
@@ -16,9 +16,10 @@ import {
|
|
|
16
16
|
import { ensureRpcServer } from "./Socket";
|
|
17
17
|
import { BrowserWindow } from "./BrowserWindow";
|
|
18
18
|
import { createSurfaceCapImpl, getPopupMetricsSnapshot } from "./SurfaceManager";
|
|
19
|
+
import { createWindowCapImpl } from "./windowCap";
|
|
19
20
|
import "./SurfaceBrowserIPC";
|
|
20
21
|
import { log, logLevelToInt } from "../log";
|
|
21
|
-
import { RuntimeCap, SurfaceCap, PageReportingCap, IpcError, type ImplOf } from "../../rpc/index";
|
|
22
|
+
import { RuntimeCap, WindowCap, SurfaceCap, PageReportingCap, IpcError, type ImplOf } from "../../rpc/index";
|
|
22
23
|
|
|
23
24
|
import type { LogLevel } from "../log";
|
|
24
25
|
|
|
@@ -179,7 +180,8 @@ export class AppRuntime {
|
|
|
179
180
|
throw new IpcError({ code: "not_found", message: `Runtime.${name}` });
|
|
180
181
|
};
|
|
181
182
|
const impl = {
|
|
182
|
-
window: (
|
|
183
|
+
window: (_: void, ctx: Parameters<ImplOf<typeof RuntimeCap>["window"]>[1]) =>
|
|
184
|
+
ctx.exportCap(WindowCap, createWindowCapImpl(viewId)),
|
|
183
185
|
dialogs: () => notImpl("dialogs"),
|
|
184
186
|
clipboard: () => notImpl("clipboard"),
|
|
185
187
|
shell: () => notImpl("shell"),
|
|
@@ -22,6 +22,7 @@ export type WindowOptionsType = {
|
|
|
22
22
|
preload: string | null;
|
|
23
23
|
appresRoot: string | null;
|
|
24
24
|
preloadOrigins?: string[];
|
|
25
|
+
label?: string;
|
|
25
26
|
/** Setup callback fired when the window's renderer connection attaches. */
|
|
26
27
|
serve?: (conn: Connection) => void;
|
|
27
28
|
titleBarStyle: "hidden" | "hiddenInset" | "default";
|
|
@@ -63,6 +64,7 @@ export class BrowserWindow {
|
|
|
63
64
|
id = getNextWindowId();
|
|
64
65
|
private nativeAttached = false;
|
|
65
66
|
title: string;
|
|
67
|
+
label = "";
|
|
66
68
|
frame: WindowOptionsType["frame"];
|
|
67
69
|
url: string | null;
|
|
68
70
|
html: string | null;
|
|
@@ -77,6 +79,9 @@ export class BrowserWindow {
|
|
|
77
79
|
webviewId: number;
|
|
78
80
|
private closed = false;
|
|
79
81
|
private restoreMaximizedAfterMinimize = false;
|
|
82
|
+
private _focused = false;
|
|
83
|
+
private readonly handleNativeFocus = () => { lastFocusedWindowId = this.id; this._focused = true; };
|
|
84
|
+
private readonly handleNativeBlur = () => { this._focused = false; };
|
|
80
85
|
private readonly handleNativeMove = (event: unknown) => {
|
|
81
86
|
const data = (event as {
|
|
82
87
|
data?: { x?: number; y?: number; maximized?: boolean; minimized?: boolean };
|
|
@@ -122,6 +127,8 @@ export class BrowserWindow {
|
|
|
122
127
|
}
|
|
123
128
|
BrowserView.getById(this.webviewId)?.detachFromNative();
|
|
124
129
|
delete BrowserWindowMap[this.id];
|
|
130
|
+
buniteEventEmitter.off(`focus-${this.id}`, this.handleNativeFocus);
|
|
131
|
+
buniteEventEmitter.off(`blur-${this.id}`, this.handleNativeBlur);
|
|
125
132
|
buniteEventEmitter.off(`move-${this.id}`, this.handleNativeMove);
|
|
126
133
|
buniteEventEmitter.off(`resize-${this.id}`, this.handleNativeResize);
|
|
127
134
|
buniteEventEmitter.off(`close-${this.id}`, this.handleNativeClose);
|
|
@@ -132,6 +139,7 @@ export class BrowserWindow {
|
|
|
132
139
|
ensureNativeRuntime();
|
|
133
140
|
|
|
134
141
|
this.title = options.title ?? defaultOptions.title;
|
|
142
|
+
this.label = options.label ?? "";
|
|
135
143
|
this.frame = { ...defaultOptions.frame, ...options.frame };
|
|
136
144
|
this.html = options.html ?? defaultOptions.html;
|
|
137
145
|
this.preload = options.preload ?? defaultOptions.preload;
|
|
@@ -160,6 +168,15 @@ export class BrowserWindow {
|
|
|
160
168
|
this.navigationRules = options.navigationRules ?? defaultOptions.navigationRules;
|
|
161
169
|
this.sandbox = options.sandbox ?? defaultOptions.sandbox;
|
|
162
170
|
|
|
171
|
+
// Register before native create — create shows the window and the initial
|
|
172
|
+
// WM_ACTIVATE fires synchronously, so listeners must be in place first.
|
|
173
|
+
BrowserWindowMap[this.id] = this;
|
|
174
|
+
buniteEventEmitter.on(`focus-${this.id}`, this.handleNativeFocus);
|
|
175
|
+
buniteEventEmitter.on(`blur-${this.id}`, this.handleNativeBlur);
|
|
176
|
+
buniteEventEmitter.on(`move-${this.id}`, this.handleNativeMove);
|
|
177
|
+
buniteEventEmitter.on(`resize-${this.id}`, this.handleNativeResize);
|
|
178
|
+
buniteEventEmitter.on(`close-${this.id}`, this.handleNativeClose);
|
|
179
|
+
|
|
163
180
|
const native = getNativeLibrary();
|
|
164
181
|
this.nativeAttached =
|
|
165
182
|
native?.symbols.bunite_window_create(
|
|
@@ -182,12 +199,6 @@ export class BrowserWindow {
|
|
|
182
199
|
);
|
|
183
200
|
}
|
|
184
201
|
|
|
185
|
-
BrowserWindowMap[this.id] = this;
|
|
186
|
-
buniteEventEmitter.on(`focus-${this.id}`, () => { lastFocusedWindowId = this.id; });
|
|
187
|
-
buniteEventEmitter.on(`move-${this.id}`, this.handleNativeMove);
|
|
188
|
-
buniteEventEmitter.on(`resize-${this.id}`, this.handleNativeResize);
|
|
189
|
-
buniteEventEmitter.on(`close-${this.id}`, this.handleNativeClose);
|
|
190
|
-
|
|
191
202
|
const webview = new BrowserView({
|
|
192
203
|
url: this.url,
|
|
193
204
|
html: this.html,
|
|
@@ -223,6 +234,15 @@ export class BrowserWindow {
|
|
|
223
234
|
return Object.values(BrowserWindowMap);
|
|
224
235
|
}
|
|
225
236
|
|
|
237
|
+
/** The window owning a given view id — its main webview, or a surface view
|
|
238
|
+
* whose `windowId` points back to the window. */
|
|
239
|
+
static getByWebviewId(viewId: number) {
|
|
240
|
+
const direct = Object.values(BrowserWindowMap).find((w) => w.webviewId === viewId);
|
|
241
|
+
if (direct) return direct;
|
|
242
|
+
const view = BrowserView.getById(viewId) as { windowId?: number } | undefined;
|
|
243
|
+
return view?.windowId != null ? BrowserWindowMap[view.windowId] : undefined;
|
|
244
|
+
}
|
|
245
|
+
|
|
226
246
|
get webview(): BrowserView | undefined {
|
|
227
247
|
return BrowserView.getById(this.webviewId) as BrowserView | undefined;
|
|
228
248
|
}
|
|
@@ -234,6 +254,11 @@ export class BrowserWindow {
|
|
|
234
254
|
}
|
|
235
255
|
}
|
|
236
256
|
|
|
257
|
+
/** Best-effort — no native focus FFI yet; show() brings the window up. */
|
|
258
|
+
focus() {
|
|
259
|
+
this.show();
|
|
260
|
+
}
|
|
261
|
+
|
|
237
262
|
close() {
|
|
238
263
|
if (this.closed) {
|
|
239
264
|
return;
|
|
@@ -258,6 +283,8 @@ export class BrowserWindow {
|
|
|
258
283
|
this.nativeAttached = false;
|
|
259
284
|
}
|
|
260
285
|
delete BrowserWindowMap[this.id];
|
|
286
|
+
buniteEventEmitter.off(`focus-${this.id}`, this.handleNativeFocus);
|
|
287
|
+
buniteEventEmitter.off(`blur-${this.id}`, this.handleNativeBlur);
|
|
261
288
|
buniteEventEmitter.off(`move-${this.id}`, this.handleNativeMove);
|
|
262
289
|
buniteEventEmitter.off(`resize-${this.id}`, this.handleNativeResize);
|
|
263
290
|
buniteEventEmitter.off(`close-${this.id}`, this.handleNativeClose);
|
|
@@ -356,6 +383,18 @@ export class BrowserWindow {
|
|
|
356
383
|
return minimized;
|
|
357
384
|
}
|
|
358
385
|
|
|
386
|
+
isFocused() {
|
|
387
|
+
return this._focused;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
toggleMaximize() {
|
|
391
|
+
if (this.isMaximized()) this.unmaximize(); else this.maximize();
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
getState() {
|
|
395
|
+
return { maximized: this.isMaximized(), minimized: this.isMinimized(), focused: this._focused };
|
|
396
|
+
}
|
|
397
|
+
|
|
359
398
|
setTitle(title: string) {
|
|
360
399
|
this.title = title;
|
|
361
400
|
if (this.nativeAttached) {
|
|
@@ -374,6 +413,13 @@ export class BrowserWindow {
|
|
|
374
413
|
return this.frame;
|
|
375
414
|
}
|
|
376
415
|
|
|
416
|
+
/** Start an OS-driven window move drag. Call from a renderer mousedown on a
|
|
417
|
+
* custom titlebar region; the OS tracks the drag through mouse-up. */
|
|
418
|
+
beginMoveDrag() {
|
|
419
|
+
if (!this.nativeAttached) return;
|
|
420
|
+
getNativeLibrary()?.symbols.bunite_window_begin_move_drag(this.id);
|
|
421
|
+
}
|
|
422
|
+
|
|
377
423
|
on(name: "close-requested" | "close" | "focus" | "blur" | "move" | "resize", handler: (event: unknown) => void) {
|
|
378
424
|
const specificName = `${name}-${this.id}`;
|
|
379
425
|
buniteEventEmitter.on(specificName, handler);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { BrowserWindow } from "./BrowserWindow";
|
|
2
|
+
import {
|
|
3
|
+
BrowserWindowCap, WindowCap, IpcError,
|
|
4
|
+
type ImplOf, type WindowState,
|
|
5
|
+
} from "../../rpc/index";
|
|
6
|
+
import { Stream } from "../../rpc/stream";
|
|
7
|
+
|
|
8
|
+
function browserWindowImpl(win: BrowserWindow): ImplOf<typeof BrowserWindowCap> {
|
|
9
|
+
return {
|
|
10
|
+
focus: () => win.focus(),
|
|
11
|
+
close: () => win.close(),
|
|
12
|
+
setBounds: ({ x, y, w, h }) => win.setFrame(x, y, w, h),
|
|
13
|
+
setTitle: ({ title }) => win.setTitle(title),
|
|
14
|
+
id: () => win.id,
|
|
15
|
+
label: () => win.label,
|
|
16
|
+
minimize: () => win.minimize(),
|
|
17
|
+
unminimize: () => win.unminimize(),
|
|
18
|
+
maximize: () => win.maximize(),
|
|
19
|
+
unmaximize: () => win.unmaximize(),
|
|
20
|
+
toggleMaximize: () => win.toggleMaximize(),
|
|
21
|
+
beginMoveDrag: () => win.beginMoveDrag(),
|
|
22
|
+
getState: () => win.getState(),
|
|
23
|
+
stateWatch: () => Stream.from<WindowState>((emit, signal) => {
|
|
24
|
+
let last = "";
|
|
25
|
+
const push = () => {
|
|
26
|
+
const s = win.getState();
|
|
27
|
+
const key = `${s.maximized}|${s.minimized}|${s.focused}`;
|
|
28
|
+
if (key === last) return;
|
|
29
|
+
last = key;
|
|
30
|
+
emit(s);
|
|
31
|
+
};
|
|
32
|
+
push(); // initial snapshot
|
|
33
|
+
const offs = [
|
|
34
|
+
win.on("focus", push), win.on("blur", push),
|
|
35
|
+
win.on("move", push), win.on("resize", push),
|
|
36
|
+
];
|
|
37
|
+
signal.addEventListener("abort", () => { for (const off of offs) off(); });
|
|
38
|
+
}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function resolve(args: { id?: number; label?: string }): BrowserWindow | undefined {
|
|
43
|
+
if (args.id != null) return BrowserWindow.getById(args.id);
|
|
44
|
+
if (args.label) return BrowserWindow.getAll().find((w) => w.label === args.label);
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** WindowCap impl for the renderer of `viewId`. `current()` resolves the owning
|
|
49
|
+
* window host-side from the session's viewId — never from a page-supplied id. */
|
|
50
|
+
export function createWindowCapImpl(viewId: number): ImplOf<typeof WindowCap> {
|
|
51
|
+
return {
|
|
52
|
+
create: ({ url, title, bounds, label }, ctx) => {
|
|
53
|
+
const win = new BrowserWindow({
|
|
54
|
+
url, title, label,
|
|
55
|
+
frame: { x: bounds?.x ?? 80, y: bounds?.y ?? 80, width: bounds?.w ?? 1280, height: bounds?.h ?? 900 },
|
|
56
|
+
});
|
|
57
|
+
return ctx.exportCap(BrowserWindowCap, browserWindowImpl(win));
|
|
58
|
+
},
|
|
59
|
+
list: (_void, ctx) =>
|
|
60
|
+
BrowserWindow.getAll().map((w) => ctx.exportCap(BrowserWindowCap, browserWindowImpl(w))),
|
|
61
|
+
current: (_void, ctx) => {
|
|
62
|
+
const win = BrowserWindow.getByWebviewId(viewId);
|
|
63
|
+
if (!win) throw new IpcError({ code: "not_found", message: "no window for this view" });
|
|
64
|
+
return ctx.exportCap(BrowserWindowCap, browserWindowImpl(win));
|
|
65
|
+
},
|
|
66
|
+
focus: (args) => { resolve(args)?.focus(); },
|
|
67
|
+
close: (args) => { resolve(args)?.close(); },
|
|
68
|
+
};
|
|
69
|
+
}
|
package/src/host/native.ts
CHANGED
|
@@ -73,6 +73,7 @@ type NativeSymbols = {
|
|
|
73
73
|
width: number,
|
|
74
74
|
height: number
|
|
75
75
|
) => void;
|
|
76
|
+
bunite_window_begin_move_drag: (windowId: number) => void;
|
|
76
77
|
bunite_view_create: (
|
|
77
78
|
viewId: number,
|
|
78
79
|
windowId: number,
|
|
@@ -263,6 +264,10 @@ const nativeSymbolDefinitions = {
|
|
|
263
264
|
args: [FFIType.u32, FFIType.f64, FFIType.f64, FFIType.f64, FFIType.f64],
|
|
264
265
|
returns: FFIType.void
|
|
265
266
|
},
|
|
267
|
+
bunite_window_begin_move_drag: {
|
|
268
|
+
args: [FFIType.u32],
|
|
269
|
+
returns: FFIType.void
|
|
270
|
+
},
|
|
266
271
|
bunite_view_create: {
|
|
267
272
|
args: [
|
|
268
273
|
FFIType.u32,
|
|
@@ -918,7 +923,7 @@ export async function initNativeRuntime(
|
|
|
918
923
|
throw new Error(`bunite: failed to load native library at ${artifacts.nativeLibPath}.`);
|
|
919
924
|
}
|
|
920
925
|
|
|
921
|
-
const EXPECTED_ABI =
|
|
926
|
+
const EXPECTED_ABI = 12;
|
|
922
927
|
const nativeAbi = nativeLibrary.symbols.bunite_abi_version();
|
|
923
928
|
if (nativeAbi !== EXPECTED_ABI) {
|
|
924
929
|
throw new Error(
|
|
@@ -113,6 +113,26 @@ extern "C" BUNITE_EXPORT void bunite_window_set_frame(
|
|
|
113
113
|
});
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
extern "C" BUNITE_EXPORT void bunite_window_begin_move_drag(uint32_t window_id) {
|
|
117
|
+
// GTK4 begin_move via default seat pointer (no-arg API → best-effort).
|
|
118
|
+
// GDK_CURRENT_TIME may be rejected by Wayland (validates the event serial).
|
|
119
|
+
runOnUiThreadSync([=]() {
|
|
120
|
+
auto* s = bunite_linux::findWindow(window_id);
|
|
121
|
+
if (!s) return;
|
|
122
|
+
GdkSurface* surface = gtk_native_get_surface(GTK_NATIVE(s->window));
|
|
123
|
+
if (!surface || !GDK_IS_TOPLEVEL(surface)) return;
|
|
124
|
+
GdkDisplay* display = gtk_widget_get_display(GTK_WIDGET(s->window));
|
|
125
|
+
GdkSeat* seat = gdk_display_get_default_seat(display);
|
|
126
|
+
GdkDevice* pointer = seat ? gdk_seat_get_pointer(seat) : nullptr;
|
|
127
|
+
if (!pointer) return;
|
|
128
|
+
double px = 0, py = 0;
|
|
129
|
+
GdkModifierType mask;
|
|
130
|
+
if (!gdk_surface_get_device_position(surface, pointer, &px, &py, &mask)) return;
|
|
131
|
+
gdk_toplevel_begin_move(GDK_TOPLEVEL(surface), pointer, /*button=*/1,
|
|
132
|
+
px, py, GDK_CURRENT_TIME);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
116
136
|
extern "C" BUNITE_EXPORT bool bunite_view_create(
|
|
117
137
|
uint32_t view_id, uint32_t window_id,
|
|
118
138
|
const char* url, const char* html, const char* preload,
|
|
@@ -20,7 +20,7 @@ using bunite_mac::runOnUiThreadSync;
|
|
|
20
20
|
|
|
21
21
|
namespace {
|
|
22
22
|
|
|
23
|
-
constexpr int32_t kBuniteAbiVersion =
|
|
23
|
+
constexpr int32_t kBuniteAbiVersion = 12;
|
|
24
24
|
|
|
25
25
|
// warn-once — avoid log spam from tight JS call loops.
|
|
26
26
|
#define BUNITE_MAC_TODO(name) \
|
|
@@ -243,6 +243,21 @@ extern "C" BUNITE_EXPORT void bunite_window_set_frame(
|
|
|
243
243
|
});
|
|
244
244
|
}
|
|
245
245
|
|
|
246
|
+
extern "C" BUNITE_EXPORT void bunite_window_begin_move_drag(uint32_t window_id) {
|
|
247
|
+
// Best-effort: the mousedown arrives via RPC, so NSApp.currentEvent is usually
|
|
248
|
+
// nil/stale here. Gate on a mouse-down event — performWindowDragWithEvent:
|
|
249
|
+
// throws on a non-mouse event. A robust path needs the event reconstructed
|
|
250
|
+
// from the RPC; deferred until mac is actively exercised.
|
|
251
|
+
runOnUiThreadSync([=]() {
|
|
252
|
+
auto* s = bunite_mac::findWindow(window_id);
|
|
253
|
+
NSEvent* ev = NSApp.currentEvent;
|
|
254
|
+
if (s && ev &&
|
|
255
|
+
(ev.type == NSEventTypeLeftMouseDown || ev.type == NSEventTypeLeftMouseDragged)) {
|
|
256
|
+
[s->window performWindowDragWithEvent:ev];
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
246
261
|
// ---------------------------------------------------------------------------
|
|
247
262
|
// View FFI.
|
|
248
263
|
// ---------------------------------------------------------------------------
|
|
@@ -70,6 +70,10 @@ BUNITE_EXPORT void bunite_window_set_frame(
|
|
|
70
70
|
double width,
|
|
71
71
|
double height
|
|
72
72
|
);
|
|
73
|
+
/** Start an OS-driven window move drag (frameless titlebar). Call from a
|
|
74
|
+
* page mousedown; the OS handles tracking through mouse-up. No-op if the
|
|
75
|
+
* window is unknown. */
|
|
76
|
+
BUNITE_EXPORT void bunite_window_begin_move_drag(uint32_t window_id);
|
|
73
77
|
|
|
74
78
|
BUNITE_EXPORT bool bunite_view_create(
|
|
75
79
|
uint32_t view_id,
|
|
@@ -730,11 +730,13 @@ ViewHost* getViewHostById(uint32_t view_id) {
|
|
|
730
730
|
}
|
|
731
731
|
|
|
732
732
|
DWORD makeWindowStyle(const std::wstring& title_bar_style) {
|
|
733
|
-
DWORD style = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
|
|
734
733
|
if (title_bar_style == L"hidden" || title_bar_style == L"hiddenInset") {
|
|
735
|
-
|
|
734
|
+
// WS_POPUP, not `WS_OVERLAPPEDWINDOW & ~WS_CAPTION`: the latter keeps
|
|
735
|
+
// WS_SYSMENU, so Windows re-adds WS_CAPTION at create. WS_THICKFRAME keeps
|
|
736
|
+
// snap + resize; the frame edge is reclaimed in WM_NCCALCSIZE.
|
|
737
|
+
return WS_POPUP | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPCHILDREN;
|
|
736
738
|
}
|
|
737
|
-
return
|
|
739
|
+
return WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
|
|
738
740
|
}
|
|
739
741
|
|
|
740
742
|
// ---------------------------------------------------------------------------
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
using bunite_win::runOnUiThreadSync;
|
|
25
25
|
using bunite_win::runOnCefUiThreadSync;
|
|
26
26
|
|
|
27
|
-
static constexpr int32_t BUNITE_ABI_VERSION =
|
|
27
|
+
static constexpr int32_t BUNITE_ABI_VERSION = 12;
|
|
28
28
|
|
|
29
29
|
namespace {
|
|
30
30
|
|
|
@@ -641,6 +641,19 @@ extern "C" BUNITE_EXPORT void bunite_window_set_frame(
|
|
|
641
641
|
});
|
|
642
642
|
}
|
|
643
643
|
|
|
644
|
+
extern "C" BUNITE_EXPORT void bunite_window_begin_move_drag(uint32_t window_id) {
|
|
645
|
+
// CEF runs Bun on a separate thread, so WM_NCLBUTTONDOWN's modal move loop
|
|
646
|
+
// doesn't freeze JS — keep the OS-native drag (Win11 snap/aero-shake). Post
|
|
647
|
+
// to the HWND-owning Win32 UI thread (ReleaseCapture + the loop are
|
|
648
|
+
// thread-local there).
|
|
649
|
+
bunite_win::postUiTask([window_id]() {
|
|
650
|
+
auto* window = bunite_win::getWindowHostById(window_id);
|
|
651
|
+
if (!window || !window->hwnd) return;
|
|
652
|
+
ReleaseCapture();
|
|
653
|
+
SendMessageW(window->hwnd, WM_NCLBUTTONDOWN, HTCAPTION, 0);
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
|
|
644
657
|
extern "C" BUNITE_EXPORT bool bunite_view_create(
|
|
645
658
|
uint32_t view_id,
|
|
646
659
|
uint32_t window_id,
|
|
@@ -81,7 +81,23 @@ static LRESULT CALLBACK buniteWindowProc(HWND hwnd, UINT message, WPARAM w_param
|
|
|
81
81
|
return DefWindowProcW(hwnd, message, w_param, l_param);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
const bool frameless = window &&
|
|
85
|
+
(window->title_bar_style == L"hidden" || window->title_bar_style == L"hiddenInset");
|
|
86
|
+
|
|
84
87
|
switch (message) {
|
|
88
|
+
case WM_NCCALCSIZE: {
|
|
89
|
+
// Reclaim the WS_THICKFRAME edge so the frameless webview fills the window
|
|
90
|
+
// (else a DWM frame band shows). Maximized (work-area clamped) reclaims all
|
|
91
|
+
// edges; restored reclaims only the top, keeping L/R/B resize borders.
|
|
92
|
+
if (w_param != TRUE || !frameless) break;
|
|
93
|
+
auto* p = reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param);
|
|
94
|
+
if (IsZoomed(hwnd)) return 0;
|
|
95
|
+
LONG top = p->rgrc[0].top;
|
|
96
|
+
LRESULT r = DefWindowProcW(hwnd, message, w_param, l_param);
|
|
97
|
+
p->rgrc[0].top = top;
|
|
98
|
+
return r;
|
|
99
|
+
}
|
|
100
|
+
|
|
85
101
|
case WM_SETFOCUS:
|
|
86
102
|
if (window) {
|
|
87
103
|
emitWindowEvent(window->id, "focus");
|
|
@@ -111,6 +127,24 @@ static LRESULT CALLBACK buniteWindowProc(HWND hwnd, UINT message, WPARAM w_param
|
|
|
111
127
|
case WM_ERASEBKGND:
|
|
112
128
|
return 1;
|
|
113
129
|
|
|
130
|
+
case WM_GETMINMAXINFO:
|
|
131
|
+
// Frameless (WS_POPUP) maximize clamps to the monitor work area (else
|
|
132
|
+
// covers the taskbar).
|
|
133
|
+
if (window && (window->title_bar_style == L"hidden" || window->title_bar_style == L"hiddenInset")) {
|
|
134
|
+
HMONITOR mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
|
|
135
|
+
MONITORINFO mi{ sizeof(mi) };
|
|
136
|
+
if (GetMonitorInfoW(mon, &mi)) {
|
|
137
|
+
auto* mmi = reinterpret_cast<MINMAXINFO*>(l_param);
|
|
138
|
+
mmi->ptMaxPosition.x = mi.rcWork.left - mi.rcMonitor.left;
|
|
139
|
+
mmi->ptMaxPosition.y = mi.rcWork.top - mi.rcMonitor.top;
|
|
140
|
+
mmi->ptMaxSize.x = mi.rcWork.right - mi.rcWork.left;
|
|
141
|
+
mmi->ptMaxSize.y = mi.rcWork.bottom - mi.rcWork.top;
|
|
142
|
+
mmi->ptMaxTrackSize = mmi->ptMaxSize;
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
break;
|
|
147
|
+
|
|
114
148
|
case WM_SIZE:
|
|
115
149
|
if (window) {
|
|
116
150
|
syncWindowFrame(window);
|
|
@@ -16,7 +16,7 @@ void setViewInputPassthrough(ViewHost* v, bool passthrough);
|
|
|
16
16
|
|
|
17
17
|
extern "C" {
|
|
18
18
|
|
|
19
|
-
BUNITE_EXPORT int32_t bunite_abi_version(void) { return
|
|
19
|
+
BUNITE_EXPORT int32_t bunite_abi_version(void) { return 12; }
|
|
20
20
|
|
|
21
21
|
BUNITE_EXPORT void bunite_set_log_level(int32_t level) {
|
|
22
22
|
if (level < 0) level = 0;
|
|
@@ -90,8 +90,11 @@ BUNITE_EXPORT void bunite_window_show(uint32_t window_id) {
|
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
BUNITE_EXPORT void bunite_window_close(uint32_t window_id) {
|
|
93
|
+
// WM_CLOSE (not DestroyWindow) so it routes through the vetoable
|
|
94
|
+
// close-requested path + destroyWindow cleanup (windows_by_id erase +
|
|
95
|
+
// all-windows-closed), matching the CEF backend.
|
|
93
96
|
WindowHost* w = getWindow(window_id);
|
|
94
|
-
if (w && w->hwnd)
|
|
97
|
+
if (w && w->hwnd) SendMessageW(w->hwnd, WM_CLOSE, 0, 0);
|
|
95
98
|
}
|
|
96
99
|
|
|
97
100
|
BUNITE_EXPORT void bunite_window_set_title(uint32_t window_id, const char* title) {
|
|
@@ -140,6 +143,41 @@ BUNITE_EXPORT void bunite_window_set_frame(uint32_t window_id,
|
|
|
140
143
|
}
|
|
141
144
|
}
|
|
142
145
|
|
|
146
|
+
// Capture-based move-drag — windowProc follows WM_MOUSEMOVE, ends on
|
|
147
|
+
// WM_LBUTTONUP/CAPTURECHANGED/CANCELMODE/DESTROY (webview2_runtime.cpp). No
|
|
148
|
+
// WM_NCLBUTTONDOWN modal loop: it would freeze the shared Bun/UI thread for
|
|
149
|
+
// the whole drag. Trade-off: no Win11 snap/aero-shake.
|
|
150
|
+
BUNITE_EXPORT void bunite_window_begin_move_drag(uint32_t window_id) {
|
|
151
|
+
WindowHost* win = getWindow(window_id);
|
|
152
|
+
if (!win || !win->hwnd || win->drag_active) return;
|
|
153
|
+
if (!(GetAsyncKeyState(VK_LBUTTON) & 0x8000)) return; // button already released
|
|
154
|
+
POINT cur;
|
|
155
|
+
if (!GetCursorPos(&cur)) return;
|
|
156
|
+
|
|
157
|
+
if (IsZoomed(win->hwnd)) { // restore under the cursor before dragging
|
|
158
|
+
RECT maxRect{};
|
|
159
|
+
WINDOWPLACEMENT wp{ sizeof(wp) };
|
|
160
|
+
GetWindowRect(win->hwnd, &maxRect);
|
|
161
|
+
GetWindowPlacement(win->hwnd, &wp);
|
|
162
|
+
const int maxW = maxRect.right - maxRect.left;
|
|
163
|
+
const int restoredW = wp.rcNormalPosition.right - wp.rcNormalPosition.left;
|
|
164
|
+
const double fx = maxW > 0 ? double(cur.x - maxRect.left) / maxW : 0.5;
|
|
165
|
+
ShowWindow(win->hwnd, SW_RESTORE);
|
|
166
|
+
win->maximized = false;
|
|
167
|
+
SetWindowPos(win->hwnd, nullptr, cur.x - static_cast<int>(restoredW * fx),
|
|
168
|
+
maxRect.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
|
169
|
+
win = getWindow(window_id); // re-validate: SW_RESTORE dispatched messages
|
|
170
|
+
if (!win || !win->hwnd) return;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
RECT r;
|
|
174
|
+
if (!GetWindowRect(win->hwnd, &r)) return;
|
|
175
|
+
win->drag_anchor_cursor = cur;
|
|
176
|
+
win->drag_anchor_origin = { r.left, r.top };
|
|
177
|
+
win->drag_active = true;
|
|
178
|
+
SetCapture(win->hwnd);
|
|
179
|
+
}
|
|
180
|
+
|
|
143
181
|
// ---- views ------------------------------------------------------------
|
|
144
182
|
|
|
145
183
|
BUNITE_EXPORT bool bunite_view_create(
|
|
@@ -123,6 +123,11 @@ struct WindowHost {
|
|
|
123
123
|
std::atomic<bool> close_pending{false};
|
|
124
124
|
std::atomic<bool> closing{false};
|
|
125
125
|
std::vector<ViewHost*> views;
|
|
126
|
+
// Capture-based move-drag (no WM_NCLBUTTONDOWN modal loop — see
|
|
127
|
+
// bunite_window_begin_move_drag + windowProc).
|
|
128
|
+
bool drag_active = false;
|
|
129
|
+
POINT drag_anchor_cursor{}; // screen cursor at drag start
|
|
130
|
+
POINT drag_anchor_origin{}; // window top-left at drag start
|
|
126
131
|
};
|
|
127
132
|
|
|
128
133
|
struct RuntimeState {
|
|
@@ -264,13 +264,103 @@ static void layoutViewsForWindow(WindowHost* w) {
|
|
|
264
264
|
for (ViewHost* v : w->views) applyViewLayout(v);
|
|
265
265
|
}
|
|
266
266
|
|
|
267
|
+
// Set drag_active=false before ReleaseCapture so the WM_CAPTURECHANGED it
|
|
268
|
+
// posts is a no-op (re-entrancy guard).
|
|
269
|
+
static void endMoveDrag(WindowHost* w, HWND hwnd) {
|
|
270
|
+
w->drag_active = false;
|
|
271
|
+
if (GetCapture() == hwnd) ReleaseCapture();
|
|
272
|
+
}
|
|
273
|
+
|
|
267
274
|
LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
|
|
268
275
|
switch (msg) {
|
|
276
|
+
case WM_NCCALCSIZE: {
|
|
277
|
+
// Frameless windows keep WS_THICKFRAME (Win11 snap + native resize), so
|
|
278
|
+
// DefWindowProc reserves a sizing frame on every edge. The HTML titlebar
|
|
279
|
+
// fills the client rect, leaving the DWM frame exposed as thin bands.
|
|
280
|
+
if (wp != TRUE) break;
|
|
281
|
+
WindowHost* w = findWindowByHwnd(hwnd);
|
|
282
|
+
if (!w || (w->title_bar_style != L"hidden" && w->title_bar_style != L"hiddenInset"))
|
|
283
|
+
break;
|
|
284
|
+
auto* p = reinterpret_cast<NCCALCSIZE_PARAMS*>(lp);
|
|
285
|
+
// Maximized: the window rect is clamped to the work area (WM_GETMINMAXINFO),
|
|
286
|
+
// so there is no off-screen frame — reclaim every edge to fill it with no
|
|
287
|
+
// frame slivers. Restored: reclaim only the top edge so the titlebar reaches
|
|
288
|
+
// y=0 (kills the top light band); keep L/R/B borders grabbable for native
|
|
289
|
+
// resize. The top is the HTML titlebar (move region), not a resize edge.
|
|
290
|
+
if (IsZoomed(hwnd)) return 0;
|
|
291
|
+
LONG top = p->rgrc[0].top;
|
|
292
|
+
LRESULT r = DefWindowProcW(hwnd, msg, wp, lp);
|
|
293
|
+
p->rgrc[0].top = top;
|
|
294
|
+
return r;
|
|
295
|
+
}
|
|
296
|
+
case WM_MOUSEMOVE: {
|
|
297
|
+
WindowHost* w = findWindowByHwnd(hwnd);
|
|
298
|
+
if (!w || !w->drag_active) break;
|
|
299
|
+
if (!(wp & MK_LBUTTON)) { endMoveDrag(w, hwnd); return 0; }
|
|
300
|
+
POINT cur;
|
|
301
|
+
if (GetCursorPos(&cur)) {
|
|
302
|
+
SetWindowPos(hwnd, nullptr,
|
|
303
|
+
w->drag_anchor_origin.x + (cur.x - w->drag_anchor_cursor.x),
|
|
304
|
+
w->drag_anchor_origin.y + (cur.y - w->drag_anchor_cursor.y),
|
|
305
|
+
0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
|
306
|
+
}
|
|
307
|
+
return 0; // don't deref w past SetWindowPos (may re-enter windowProc)
|
|
308
|
+
}
|
|
309
|
+
case WM_LBUTTONUP: {
|
|
310
|
+
WindowHost* w = findWindowByHwnd(hwnd);
|
|
311
|
+
if (w && w->drag_active) { endMoveDrag(w, hwnd); return 0; }
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
case WM_CAPTURECHANGED:
|
|
315
|
+
case WM_CANCELMODE: {
|
|
316
|
+
WindowHost* w = findWindowByHwnd(hwnd);
|
|
317
|
+
if (w && w->drag_active) endMoveDrag(w, hwnd);
|
|
318
|
+
break;
|
|
319
|
+
}
|
|
269
320
|
case WM_SIZE: {
|
|
270
321
|
WindowHost* w = findWindowByHwnd(hwnd);
|
|
271
|
-
if (w)
|
|
322
|
+
if (!w) break;
|
|
323
|
+
layoutViewsForWindow(w);
|
|
324
|
+
RECT r{};
|
|
325
|
+
GetWindowRect(hwnd, &r);
|
|
326
|
+
std::string payload = "{\"x\":" + std::to_string(r.left) + ",\"y\":" + std::to_string(r.top) +
|
|
327
|
+
",\"width\":" + std::to_string(r.right - r.left) + ",\"height\":" + std::to_string(r.bottom - r.top) +
|
|
328
|
+
",\"maximized\":" + (wp == SIZE_MAXIMIZED ? "true" : "false") +
|
|
329
|
+
",\"minimized\":" + (wp == SIZE_MINIMIZED ? "true" : "false") + "}";
|
|
330
|
+
emitWindowEvent(w->id, "resize", payload);
|
|
272
331
|
return 0;
|
|
273
332
|
}
|
|
333
|
+
case WM_MOVE: {
|
|
334
|
+
WindowHost* w = findWindowByHwnd(hwnd);
|
|
335
|
+
if (w) {
|
|
336
|
+
RECT r{};
|
|
337
|
+
GetWindowRect(hwnd, &r);
|
|
338
|
+
emitWindowEvent(w->id, "move",
|
|
339
|
+
"{\"x\":" + std::to_string(r.left) + ",\"y\":" + std::to_string(r.top) +
|
|
340
|
+
",\"maximized\":" + (IsZoomed(hwnd) ? "true" : "false") +
|
|
341
|
+
",\"minimized\":" + (IsIconic(hwnd) ? "true" : "false") + "}");
|
|
342
|
+
}
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
case WM_GETMINMAXINFO: {
|
|
346
|
+
// Frameless (WS_POPUP) windows maximize over the taskbar unless clamped
|
|
347
|
+
// to the monitor work area.
|
|
348
|
+
WindowHost* w = findWindowByHwnd(hwnd);
|
|
349
|
+
if (w && (w->title_bar_style == L"hidden" || w->title_bar_style == L"hiddenInset")) {
|
|
350
|
+
HMONITOR mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
|
|
351
|
+
MONITORINFO mi{ sizeof(mi) };
|
|
352
|
+
if (GetMonitorInfoW(mon, &mi)) {
|
|
353
|
+
auto* mmi = reinterpret_cast<MINMAXINFO*>(lp);
|
|
354
|
+
mmi->ptMaxPosition.x = mi.rcWork.left - mi.rcMonitor.left;
|
|
355
|
+
mmi->ptMaxPosition.y = mi.rcWork.top - mi.rcMonitor.top;
|
|
356
|
+
mmi->ptMaxSize.x = mi.rcWork.right - mi.rcWork.left;
|
|
357
|
+
mmi->ptMaxSize.y = mi.rcWork.bottom - mi.rcWork.top;
|
|
358
|
+
mmi->ptMaxTrackSize = mmi->ptMaxSize;
|
|
359
|
+
return 0;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
274
364
|
case WM_CLOSE: {
|
|
275
365
|
WindowHost* w = findWindowByHwnd(hwnd);
|
|
276
366
|
if (w && !w->close_pending.load()) {
|
|
@@ -281,19 +371,17 @@ LRESULT CALLBACK windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
|
|
|
281
371
|
DestroyWindow(hwnd);
|
|
282
372
|
return 0;
|
|
283
373
|
}
|
|
284
|
-
case WM_SETFOCUS:
|
|
285
374
|
case WM_ACTIVATE: {
|
|
286
375
|
WindowHost* w = findWindowByHwnd(hwnd);
|
|
287
|
-
|
|
376
|
+
// Top-level activation drives focus (not WM_SETFOCUS, which can be child focus).
|
|
377
|
+
if (w) emitWindowEvent(w->id, LOWORD(wp) == WA_INACTIVE ? "blur" : "focus");
|
|
288
378
|
break;
|
|
289
379
|
}
|
|
290
|
-
case
|
|
380
|
+
case WM_DESTROY: {
|
|
291
381
|
WindowHost* w = findWindowByHwnd(hwnd);
|
|
292
|
-
if (w)
|
|
293
|
-
break;
|
|
294
|
-
}
|
|
295
|
-
case WM_DESTROY:
|
|
382
|
+
if (w && w->drag_active) endMoveDrag(w, hwnd);
|
|
296
383
|
return 0;
|
|
384
|
+
}
|
|
297
385
|
}
|
|
298
386
|
return DefWindowProcW(hwnd, msg, wp, lp);
|
|
299
387
|
}
|
|
@@ -515,6 +603,14 @@ bool createWindow(uint32_t window_id, double x, double y, double w, double h,
|
|
|
515
603
|
g_runtime.windows_by_id[window_id] = host;
|
|
516
604
|
}
|
|
517
605
|
|
|
606
|
+
// CreateWindowExW dispatched WM_NCCALCSIZE before the window was registered,
|
|
607
|
+
// so the frameless top-frame reclaim (windowProc) couldn't run yet. Force a
|
|
608
|
+
// frame recalc now that findWindowByHwnd can resolve it.
|
|
609
|
+
if (host->title_bar_style == L"hidden" || host->title_bar_style == L"hiddenInset") {
|
|
610
|
+
SetWindowPos(hwnd, nullptr, 0, 0, 0, 0,
|
|
611
|
+
SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
|
612
|
+
}
|
|
613
|
+
|
|
518
614
|
if (maximized) ShowWindow(hwnd, SW_MAXIMIZE);
|
|
519
615
|
else if (minimized) ShowWindow(hwnd, SW_MINIMIZE);
|
|
520
616
|
else if (!hidden) ShowWindow(hwnd, SW_SHOW);
|
|
@@ -946,6 +1042,9 @@ static void attachControllerCallbacks(ViewHost* view) {
|
|
|
946
1042
|
&tok);
|
|
947
1043
|
|
|
948
1044
|
// Disable default WV2 dialog UI so ScriptDialogOpening drives all dialogs.
|
|
1045
|
+
// NB: NonClientRegionSupport (app-region:drag) is intentionally NOT enabled —
|
|
1046
|
+
// its native window-move runs a modal loop on the shared Bun/UI thread and
|
|
1047
|
+
// freezes JS for the whole drag (spike-confirmed). WV2 drag stays capture-based.
|
|
949
1048
|
ComPtr<ICoreWebView2Settings> settings;
|
|
950
1049
|
if (SUCCEEDED(view->webview->get_Settings(&settings)) && settings) {
|
|
951
1050
|
settings->put_AreDefaultScriptDialogsEnabled(FALSE);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var gX=Symbol.for("bunite.rpc.CallDef"),fX=Symbol.for("bunite.rpc.StreamDef"),pX=Symbol.for("bunite.rpc.CapDef"),uX=Symbol.for("bunite.rpc.CapRefToken"),lX=Symbol.for("bunite.rpc.CapArrayToken"),dX=Symbol.for("bunite.rpc.CapRecordToken"),y0=Symbol.for("bunite.rpc.Schema");function t8(X){return{[uX]:!0,cap:X}}t8.array=(X)=>({[lX]:!0,cap:X});t8.record=(X)=>({[dX]:!0,cap:X});var n=t8;function C8(X){return typeof X==="object"&&X!==null&&X[uX]===!0}function E8(X){return typeof X==="object"&&X!==null&&X[lX]===!0}function j8(X){return typeof X==="object"&&X!==null&&X[dX]===!0}function x8(X){return typeof X==="object"&&X!==null&&X[gX]===!0}function w8(X){return typeof X==="object"&&X!==null&&X[fX]===!0}function z(X){return{[gX]:!0,idempotent:!!X?.idempotent,returns:X?.returns}}function G8(X){return{[fX]:!0,hint:X?.hint}}function i(X,$,Q){return{[pX]:!0,name:X,version:Q?.version!=null?String(Q.version):void 0,methods:$,disposal:Q?.disposal??void 0}}function b8(X){return typeof X==="object"&&X!==null&&X[pX]===!0}function e8(X){return typeof X==="object"&&X!==null&&X[y0]===!0}var $X;try{$X=new TextDecoder}catch(X){}var _,s,J=0;var H0=[],QX=H0,ZX=0,b={},E,J8,o=0,e=0,p,H8,l=[],C,cX={useRecords:!1,mapsAsObjects:!0};class y8{}var qX=new y8;qX.name="MessagePack 0xC1";var N8=!1,nX=2,oX,sX,iX;class X8{constructor(X){if(X){if(X.useRecords===!1&&X.mapsAsObjects===void 0)X.mapsAsObjects=!0;if(X.sequential&&X.trusted!==!1){if(X.trusted=!0,!X.structures&&X.useRecords!=!1){if(X.structures=[],!X.maxSharedStructures)X.maxSharedStructures=0}}if(X.structures)X.structures.sharedLength=X.structures.length;else if(X.getStructures)(X.structures=[]).uninitialized=!0,X.structures.sharedLength=0;if(X.int64AsNumber)X.int64AsType="number"}Object.assign(this,X)}unpack(X,$){if(_)return K0(()=>{return k8(),this?this.unpack(X,$):X8.prototype.unpack.call(cX,X,$)});if(!X.buffer&&X.constructor===ArrayBuffer)X=typeof Buffer<"u"?Buffer.from(X):new Uint8Array(X);if(typeof $==="object")s=$.end||X.length,J=$.start||0;else J=0,s=$>-1?$:X.length;ZX=0,e=0,J8=null,QX=H0,p=null,_=X;try{C=X.dataView||(X.dataView=new DataView(X.buffer,X.byteOffset,X.byteLength))}catch(Q){if(_=null,X instanceof Uint8Array)throw Q;throw Error("Source must be a Uint8Array or Buffer but was a "+(X&&typeof X=="object"?X.constructor.name:typeof X))}if(this instanceof X8){if(b=this,this.structures)return E=this.structures,I8($);else if(!E||E.length>0)E=[]}else if(b=cX,!E||E.length>0)E=[];return I8($)}unpackMultiple(X,$){let Q,Z=0;try{N8=!0;let H=X.length,q=this?this.unpack(X,H):v8.unpack(X,H);if($){if($(q,Z,J)===!1)return;while(J<H)if(Z=J,$(I8(),Z,J)===!1)return}else{Q=[q];while(J<H)Z=J,Q.push(I8());return Q}}catch(H){throw H.lastPosition=Z,H.values=Q,H}finally{N8=!1,k8()}}_mergeStructures(X,$){if(sX)X=sX.call(this,X);if(X=X||[],Object.isFrozen(X))X=X.map((Q)=>Q.slice(0));for(let Q=0,Z=X.length;Q<Z;Q++){let H=X[Q];if(H){if(H.isShared=!0,Q>=32)H.highByte=Q-32>>5}}X.sharedLength=X.length;for(let Q in $||[])if(Q>=0){let Z=X[Q],H=$[Q];if(H){if(Z)(X.restoreStructures||(X.restoreStructures=[]))[Q]=Z;X[Q]=H}}return this.structures=X}decode(X,$){return this.unpack(X,$)}}function I8(X){try{if(!b.trusted&&!N8){let Q=E.sharedLength||0;if(Q<E.length)E.length=Q}let $;if(b.randomAccessStructure&&_[J]<64&&_[J]>=32&&oX){if($=oX(_,J,s,b),_=null,!(X&&X.lazy)&&$)$=$.toJSON();J=s}else $=h();if(p)J=p.postBundlePosition,p=null;if(N8)E.restoreStructures=null;if(J==s){if(E&&E.restoreStructures)aX();if(E=null,_=null,H8)H8=null}else if(J>s)throw Error("Unexpected end of MessagePack data");else if(!N8){let Q;try{Q=JSON.stringify($,(Z,H)=>typeof H==="bigint"?`${H}n`:H).slice(0,100)}catch(Z){Q="(JSON view not available "+Z+")"}throw Error("Data read, but end of buffer not reached "+Q)}return $}catch($){if(E&&E.restoreStructures)aX();if(k8(),$ instanceof RangeError||$.message.startsWith("Unexpected end of buffer")||J>s)$.incomplete=!0;throw $}}function aX(){for(let X in E.restoreStructures)E[X]=E.restoreStructures[X];E.restoreStructures=null}function h(){let X=_[J++];if(X<160)if(X<128)if(X<64)return X;else{let $=E[X&63]||b.getStructures&&q0()[X&63];if($){if(!$.read)$.read=JX($,X&63);return $.read()}else return X}else if(X<144)if(X-=128,b.mapsAsObjects){let $={};for(let Q=0;Q<X;Q++){let Z=N0();if(Z==="__proto__")Z="__proto_";$[Z]=h()}return $}else{let $=new Map;for(let Q=0;Q<X;Q++)$.set(h(),h());return $}else{X-=144;let $=Array(X);for(let Q=0;Q<X;Q++)$[Q]=h();if(b.freezeData)return Object.freeze($);return $}else if(X<192){let $=X-160;if(e>=J)return J8.slice(J-o,(J+=$)-o);if(e==0&&s<140){let Q=$<16?NX($):J0($);if(Q!=null)return Q}return HX($)}else{let $;switch(X){case 192:return null;case 193:if(p)if($=h(),$>0)return p[1].slice(p.position1,p.position1+=$);else return p[0].slice(p.position0,p.position0-=$);return qX;case 194:return!1;case 195:return!0;case 196:if($=_[J++],$===void 0)throw Error("Unexpected end of buffer");return XX($);case 197:return $=C.getUint16(J),J+=2,XX($);case 198:return $=C.getUint32(J),J+=4,XX($);case 199:return K8(_[J++]);case 200:return $=C.getUint16(J),J+=2,K8($);case 201:return $=C.getUint32(J),J+=4,K8($);case 202:if($=C.getFloat32(J),b.useFloat32>2){let Q=S8[(_[J]&127)<<1|_[J+1]>>7];return J+=4,(Q*$+($>0?0.5:-0.5)>>0)/Q}return J+=4,$;case 203:return $=C.getFloat64(J),J+=8,$;case 204:return _[J++];case 205:return $=C.getUint16(J),J+=2,$;case 206:return $=C.getUint32(J),J+=4,$;case 207:if(b.int64AsType==="number")$=C.getUint32(J)*4294967296,$+=C.getUint32(J+4);else if(b.int64AsType==="string")$=C.getBigUint64(J).toString();else if(b.int64AsType==="auto"){if($=C.getBigUint64(J),$<=BigInt(2)<<BigInt(52))$=Number($)}else $=C.getBigUint64(J);return J+=8,$;case 208:return C.getInt8(J++);case 209:return $=C.getInt16(J),J+=2,$;case 210:return $=C.getInt32(J),J+=4,$;case 211:if(b.int64AsType==="number")$=C.getInt32(J)*4294967296,$+=C.getUint32(J+4);else if(b.int64AsType==="string")$=C.getBigInt64(J).toString();else if(b.int64AsType==="auto"){if($=C.getBigInt64(J),$>=BigInt(-2)<<BigInt(52)&&$<=BigInt(2)<<BigInt(52))$=Number($)}else $=C.getBigInt64(J);return J+=8,$;case 212:if($=_[J++],$==114)return Q0(_[J++]&63);else{let Q=l[$];if(Q)if(Q.read)return J++,Q.read(h());else if(Q.noBuffer)return J++,Q();else return Q(_.subarray(J,++J));else throw Error("Unknown extension "+$)}case 213:if($=_[J],$==114)return J++,Q0(_[J++]&63,_[J++]);else return K8(2);case 214:return K8(4);case 215:return K8(8);case 216:return K8(16);case 217:if($=_[J++],e>=J)return J8.slice(J-o,(J+=$)-o);return v0($);case 218:if($=C.getUint16(J),J+=2,e>=J)return J8.slice(J-o,(J+=$)-o);return h0($);case 219:if($=C.getUint32(J),J+=4,e>=J)return J8.slice(J-o,(J+=$)-o);return m0($);case 220:return $=C.getUint16(J),J+=2,tX($);case 221:return $=C.getUint32(J),J+=4,tX($);case 222:return $=C.getUint16(J),J+=2,eX($);case 223:return $=C.getUint32(J),J+=4,eX($);default:if(X>=224)return X-256;if(X===void 0){let Q=Error("Unexpected end of MessagePack data");throw Q.incomplete=!0,Q}throw Error("Unknown MessagePack token "+X)}}}var S0=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function JX(X,$){function Q(){if(Q.count++>nX){let H;try{H=X.read=Function("r","return function(){return "+(b.freezeData?"Object.freeze":"")+"({"+X.map((q)=>q==="__proto__"?"__proto_:r()":S0.test(q)?q+":r()":"["+JSON.stringify(q)+"]:r()").join(",")+"})}")(h)}catch(q){return nX=1/0,Q()}if(X.highByte===0)X.read=rX($,X.read);return H()}let Z={};for(let H=0,q=X.length;H<q;H++){let G=X[H];if(G==="__proto__")G="__proto_";Z[G]=h()}if(b.freezeData)return Object.freeze(Z);return Z}if(Q.count=0,X.highByte===0)return rX($,Q);return Q}var rX=(X,$)=>{return function(){let Q=_[J++];if(Q===0)return $();let Z=X<32?-(X+(Q<<5)):X+(Q<<5),H=E[Z]||q0()[Z];if(!H)throw Error("Record id is not defined for "+Z);if(!H.read)H.read=JX(H,X);return H.read()}};function q0(){let X=K0(()=>{return _=null,b.getStructures()});return E=b._mergeStructures(X,E)}var HX=_8,v0=_8,h0=_8,m0=_8;function _8(X){let $;if(X<16){if($=NX(X))return $}if(X>64&&$X)return $X.decode(_.subarray(J,J+=X));let Q=J+X,Z=[];$="";while(J<Q){let H=_[J++];if((H&128)===0)Z.push(H);else if((H&224)===192){let q=_[J++]&63,G=(H&31)<<6|q;if(G<128)Z.push(65533);else Z.push(G)}else if((H&240)===224){let q=_[J++]&63,G=_[J++]&63,D=(H&31)<<12|q<<6|G;if(D<2048||D>=55296&&D<=57343)Z.push(65533);else Z.push(D)}else if((H&248)===240){let q=_[J++]&63,G=_[J++]&63,D=_[J++]&63,O=(H&7)<<18|q<<12|G<<6|D;if(O<65536||O>1114111)Z.push(65533);else if(O>65535)O-=65536,Z.push(O>>>10&1023|55296),O=56320|O&1023,Z.push(O);else Z.push(O)}else Z.push(65533);if(Z.length>=4096)$+=f.apply(String,Z),Z.length=0}if(Z.length>0)$+=f.apply(String,Z);return $}function tX(X){let $=Array(X);for(let Q=0;Q<X;Q++)$[Q]=h();if(b.freezeData)return Object.freeze($);return $}function eX(X){if(b.mapsAsObjects){let $={};for(let Q=0;Q<X;Q++){let Z=N0();if(Z==="__proto__")Z="__proto_";$[Z]=h()}return $}else{let $=new Map;for(let Q=0;Q<X;Q++)$.set(h(),h());return $}}var f=String.fromCharCode;function J0(X){let $=J,Q=Array(X);for(let Z=0;Z<X;Z++){let H=_[J++];if((H&128)>0){J=$;return}Q[Z]=H}return f.apply(String,Q)}function NX(X){if(X<4)if(X<2)if(X===0)return"";else{let $=_[J++];if(($&128)>1){J-=1;return}return f($)}else{let $=_[J++],Q=_[J++];if(($&128)>0||(Q&128)>0){J-=2;return}if(X<3)return f($,Q);let Z=_[J++];if((Z&128)>0){J-=3;return}return f($,Q,Z)}else{let $=_[J++],Q=_[J++],Z=_[J++],H=_[J++];if(($&128)>0||(Q&128)>0||(Z&128)>0||(H&128)>0){J-=4;return}if(X<6)if(X===4)return f($,Q,Z,H);else{let q=_[J++];if((q&128)>0){J-=5;return}return f($,Q,Z,H,q)}else if(X<8){let q=_[J++],G=_[J++];if((q&128)>0||(G&128)>0){J-=6;return}if(X<7)return f($,Q,Z,H,q,G);let D=_[J++];if((D&128)>0){J-=7;return}return f($,Q,Z,H,q,G,D)}else{let q=_[J++],G=_[J++],D=_[J++],O=_[J++];if((q&128)>0||(G&128)>0||(D&128)>0||(O&128)>0){J-=8;return}if(X<10)if(X===8)return f($,Q,Z,H,q,G,D,O);else{let M=_[J++];if((M&128)>0){J-=9;return}return f($,Q,Z,H,q,G,D,O,M)}else if(X<12){let M=_[J++],T=_[J++];if((M&128)>0||(T&128)>0){J-=10;return}if(X<11)return f($,Q,Z,H,q,G,D,O,M,T);let V=_[J++];if((V&128)>0){J-=11;return}return f($,Q,Z,H,q,G,D,O,M,T,V)}else{let M=_[J++],T=_[J++],V=_[J++],j=_[J++];if((M&128)>0||(T&128)>0||(V&128)>0||(j&128)>0){J-=12;return}if(X<14)if(X===12)return f($,Q,Z,H,q,G,D,O,M,T,V,j);else{let k=_[J++];if((k&128)>0){J-=13;return}return f($,Q,Z,H,q,G,D,O,M,T,V,j,k)}else{let k=_[J++],v=_[J++];if((k&128)>0||(v&128)>0){J-=14;return}if(X<15)return f($,Q,Z,H,q,G,D,O,M,T,V,j,k,v);let u=_[J++];if((u&128)>0){J-=15;return}return f($,Q,Z,H,q,G,D,O,M,T,V,j,k,v,u)}}}}}function X0(){let X=_[J++],$;if(X<192)$=X-160;else switch(X){case 217:$=_[J++];break;case 218:$=C.getUint16(J),J+=2;break;case 219:$=C.getUint32(J),J+=4;break;default:throw Error("Expected string")}return _8($)}function XX(X){return b.copyBuffers?Uint8Array.prototype.slice.call(_,J,J+=X):_.subarray(J,J+=X)}function K8(X){let $=_[J++];if(l[$]){let Q;return l[$](_.subarray(J,Q=J+=X),(Z)=>{J=Z;try{return h()}finally{J=Q}})}else throw Error("Unknown extension type "+$)}var $0=Array(4096);function N0(){let X=_[J++];if(X>=160&&X<192){if(X=X-160,e>=J)return J8.slice(J-o,(J+=X)-o);else if(!(e==0&&s<180))return HX(X)}else return J--,G0(h());let $=(X<<5^(X>1?C.getUint16(J):X>0?_[J]:0))&4095,Q=$0[$],Z=J,H=J+X-3,q,G=0;if(Q&&Q.bytes==X){while(Z<H){if(q=C.getUint32(Z),q!=Q[G++]){Z=1879048192;break}Z+=4}H+=3;while(Z<H)if(q=_[Z++],q!=Q[G++]){Z=1879048192;break}if(Z===H)return J=Z,Q.string;H-=3,Z=J}Q=[],$0[$]=Q,Q.bytes=X;while(Z<H)q=C.getUint32(Z),Q.push(q),Z+=4;H+=3;while(Z<H)q=_[Z++],Q.push(q);let D=X<16?NX(X):J0(X);if(D!=null)return Q.string=D;return Q.string=HX(X)}function G0(X){if(typeof X==="string")return X;if(typeof X==="number"||typeof X==="boolean"||typeof X==="bigint")return X.toString();if(X==null)return X+"";if(b.allowArraysInMapKeys&&Array.isArray(X)&&X.flat().every(($)=>["string","number","boolean","bigint"].includes(typeof $)))return X.flat().toString();throw Error(`Invalid property type for record: ${typeof X}`)}var Q0=(X,$)=>{let Q=h().map(G0),Z=X;if($!==void 0)X=X<32?-(($<<5)+X):($<<5)+X,Q.highByte=$;let H=E[X];if(H&&(H.isShared||N8))(E.restoreStructures||(E.restoreStructures=[]))[X]=H;return E[X]=Q,Q.read=JX(Q,Z),Q.read()};l[0]=()=>{};l[0].noBuffer=!0;l[66]=(X)=>{let $=X.byteLength%8||8,Q=BigInt(X[0]&128?X[0]-256:X[0]);for(let Z=1;Z<$;Z++)Q<<=BigInt(8),Q+=BigInt(X[Z]);if(X.byteLength!==$){let Z=new DataView(X.buffer,X.byteOffset,X.byteLength),H=(q,G)=>{let D=G-q;if(D<=40){let V=Z.getBigUint64(q);for(let j=q+8;j<G;j+=8)V<<=BigInt(64),V|=Z.getBigUint64(j);return V}let O=q+(D>>4<<3),M=H(q,O),T=H(O,G);return M<<BigInt((G-O)*8)|T};Q=Q<<BigInt((Z.byteLength-$)*8)|H($,Z.byteLength)}return Q};var Z0={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==="function"?AggregateError:null};l[101]=()=>{let X=h();if(!Z0[X[0]]){let $=Error(X[1],{cause:X[2]});return $.name=X[0],$}return Z0[X[0]](X[1],{cause:X[2]})};l[105]=(X)=>{if(b.structuredClone===!1)throw Error("Structured clone extension is disabled");let $=C.getUint32(J-4);if(!H8)H8=new Map;let Q=_[J],Z;if(Q>=144&&Q<160||Q==220||Q==221)Z=[];else if(Q>=128&&Q<144||Q==222||Q==223)Z=new Map;else if((Q>=199&&Q<=201||Q>=212&&Q<=216)&&_[J+1]===115)Z=new Set;else Z={};let H={target:Z};H8.set($,H);let q=h();if(!H.used)return H.target=q;else Object.assign(Z,q);if(Z instanceof Map)for(let[G,D]of q.entries())Z.set(G,D);if(Z instanceof Set)for(let G of Array.from(q))Z.add(G);return Z};l[112]=(X)=>{if(b.structuredClone===!1)throw Error("Structured clone extension is disabled");let $=C.getUint32(J-4),Q=H8.get($);return Q.used=!0,Q.target};l[115]=()=>new Set(h());var GX=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((X)=>X+"Array"),g0=typeof globalThis==="object"?globalThis:window;l[116]=(X)=>{let $=X[0],Q=Uint8Array.prototype.slice.call(X,1).buffer,Z=GX[$];if(!Z){if($===16)return Q;if($===17)return new DataView(Q);throw Error("Could not find typed array for code "+$)}return new g0[Z](Q)};l[120]=()=>{let X=h();return new RegExp(X[0],X[1])};var f0=[];l[98]=(X)=>{let $=(X[0]<<24)+(X[1]<<16)+(X[2]<<8)+X[3],Q=J;return J+=$-X.length,p=f0,p=[X0(),X0()],p.position0=0,p.position1=0,p.postBundlePosition=J,J=Q,h()};l[255]=(X)=>{if(X.length==4)return new Date((X[0]*16777216+(X[1]<<16)+(X[2]<<8)+X[3])*1000);else if(X.length==8)return new Date(((X[0]<<22)+(X[1]<<14)+(X[2]<<6)+(X[3]>>2))/1e6+((X[3]&3)*4294967296+X[4]*16777216+(X[5]<<16)+(X[6]<<8)+X[7])*1000);else if(X.length==12)return new Date(((X[0]<<24)+(X[1]<<16)+(X[2]<<8)+X[3])/1e6+((X[4]&128?-281474976710656:0)+X[6]*1099511627776+X[7]*4294967296+X[8]*16777216+(X[9]<<16)+(X[10]<<8)+X[11])*1000);else return new Date("invalid")};function K0(X){if(iX)iX();let $=s,Q=J,Z=ZX,H=o,q=e,G=J8,D=QX,O=H8,M=p,T=new Uint8Array(_.slice(0,s)),V=E,j=E.slice(0,E.length),k=b,v=N8,u=X();return s=$,J=Q,ZX=Z,o=H,e=q,J8=G,QX=D,H8=O,p=M,_=T,N8=v,E=V,E.splice(0,E.length,...j),b=k,C=new DataView(_.buffer,_.byteOffset,_.byteLength),u}function k8(){_=null,H8=null,E=null}function Y0(X){if(X.unpack)l[X.type]=X.unpack;else l[X.type]=X}var S8=Array(147);for(let X=0;X<256;X++)S8[X]=+("1e"+Math.floor(45.15-X*0.30103));var v8=new X8({useRecords:!1}),p0=v8.unpack,u0=v8.unpackMultiple,l0=v8.unpack;var d0=new Float32Array(1),C$=new Uint8Array(d0.buffer,0,4);var m8;try{m8=new TextEncoder}catch(X){}var g8,f8,D8=typeof Buffer<"u",h8=D8?function(X){return Buffer.allocUnsafeSlow(X)}:Uint8Array,O0=D8?Buffer:Uint8Array,D0=D8?4294967296:2144337920,K,A8,I,N=0,d,S=null,c0,n0=21760,o0=/[\u0080-\uFFFF]/,Y8=Symbol("record-id");class F8 extends X8{constructor(X){super(X);this.offset=0;let $,Q,Z,H,q,G=O0.prototype.utf8Write?function(Y,A){return K.utf8Write(Y,A,K.byteLength-A)}:m8&&m8.encodeInto?function(Y,A){return m8.encodeInto(Y,K.subarray(A)).written}:!1,D=this;if(!X)X={};let O=X&&X.sequential,M=X.structures||X.saveStructures,T=X.maxSharedStructures;if(T==null)T=M?32:0;if(T>8160)throw Error("Maximum maxSharedStructure is 8160");if(X.structuredClone&&X.moreTypes==null)this.moreTypes=!0;let V=X.maxOwnStructures;if(V==null)V=M?32:64;if(!this.structures&&X.useRecords!=!1)this.structures=[];let j=T>32||V+T>64,k=T+64,v=T+V+64;if(v>8256)throw Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let u=[],g=0,Q8=0;this.pack=this.encode=function(Y,A){if(!K)K=new h8(8192),I=K.dataView||(K.dataView=new DataView(K.buffer,0,8192)),N=0;if(d=K.length-10,d-N<2048)K=new h8(K.length),I=K.dataView||(K.dataView=new DataView(K.buffer,0,K.length)),d=K.length-10,N=0;else N=N+7&2147483640;if(Q=N,A&M0)N+=A&255;if(q=D.structuredClone?new Map:null,D.bundleStrings&&typeof Y!=="string")S=[],S.size=1/0;else S=null;if(H=D.structures,H){if(H.uninitialized)H=D._mergeStructures(D.getStructures());let F=H.sharedLength||0;if(F>T)throw Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+H.sharedLength);if(!H.transitions){H.transitions=Object.create(null);for(let L=0;L<F;L++){let R=H[L];if(!R)continue;let B,W=H.transitions;for(let x=0,w=R.length;x<w;x++){let t=R[x];if(B=W[t],!B)B=W[t]=Object.create(null);W=B}W[Y8]=L+64}this.lastNamedStructuresLength=F}if(!O)H.nextId=F+64}if(Z)Z=!1;let U;try{if(D.randomAccessStructure&&Y&&typeof Y==="object")if(Y.constructor===Object)mX(Y);else if(Y.constructor!==Map&&!Array.isArray(Y)&&!f8.some((L)=>Y instanceof L))mX(Y.toJSON?Y.toJSON():Y);else y(Y);else y(Y);let F=S;if(S)L0(Q,y,0);if(q&&q.idsToInsert){let L=q.idsToInsert.sort((x,w)=>x.offset>w.offset?1:-1),R=L.length,B=-1;while(F&&R>0){let x=L[--R].offset+Q;if(x<F.stringsPosition+Q&&B===-1)B=0;if(x>F.position+Q){if(B>=0)B+=6}else{if(B>=0)I.setUint32(F.position+Q,I.getUint32(F.position+Q)+B),B=-1;F=F.previous,R++}}if(B>=0&&F)I.setUint32(F.position+Q,I.getUint32(F.position+Q)+B);if(N+=L.length*6,N>d)Z8(N);D.offset=N;let W=s0(K.subarray(Q,N),L);return q=null,W}if(D.offset=N,A&A0)return K.start=Q,K.end=N,K;return K.subarray(Q,N)}catch(F){throw U=F,F}finally{if(H){if(T8(),Z&&D.saveStructures){let F=H.sharedLength||0,L=K.subarray(Q,N),R=i0(H,D);if(!U){if(D.saveStructures(R,R.isCompatible)===!1)return D.pack(Y,A);if(D.lastNamedStructuresLength=F,K.length>1073741824)K=null;return L}}}if(K.length>1073741824)K=null;if(A&z0)N=Q}};let T8=()=>{if(Q8<10)Q8++;let Y=H.sharedLength||0;if(H.length>Y&&!O)H.length=Y;if(g>1e4){if(H.transitions=null,Q8=0,g=0,u.length>0)u=[]}else if(u.length>0&&!O){for(let A=0,U=u.length;A<U;A++)u[A][Y8]=0;u=[]}},a8=(Y)=>{var A=Y.length;if(A<16)K[N++]=144|A;else if(A<65536)K[N++]=220,K[N++]=A>>8,K[N++]=A&255;else K[N++]=221,I.setUint32(N,A),N+=4;for(let U=0;U<A;U++)y(Y[U])},y=(Y)=>{if(N>d)K=Z8(N);var A=typeof Y,U;if(A==="string"){let F=Y.length;if(S&&F>=4&&F<4096){if((S.size+=F)>n0){let W,x=(S[0]?S[0].length*3+S[1].length:0)+10;if(N+x>d)K=Z8(N+x);let w;if(S.position)w=S,K[N]=200,N+=3,K[N++]=98,W=N-Q,N+=4,L0(Q,y,0),I.setUint16(W+Q-3,N-Q-W);else K[N++]=214,K[N++]=98,W=N-Q,N+=4;S=["",""],S.previous=w,S.size=0,S.position=W}let B=o0.test(Y);S[B?0:1]+=Y,K[N++]=193,y(B?-F:F);return}let L;if(F<32)L=1;else if(F<256)L=2;else if(F<65536)L=3;else L=5;let R=F*3;if(N+R>d)K=Z8(N+R);if(F<64||!G){let B,W,x,w=N+L;for(B=0;B<F;B++)if(W=Y.charCodeAt(B),W<128)K[w++]=W;else if(W<2048)K[w++]=W>>6|192,K[w++]=W&63|128;else if((W&64512)===55296&&((x=Y.charCodeAt(B+1))&64512)===56320)W=65536+((W&1023)<<10)+(x&1023),B++,K[w++]=W>>18|240,K[w++]=W>>12&63|128,K[w++]=W>>6&63|128,K[w++]=W&63|128;else K[w++]=W>>12|224,K[w++]=W>>6&63|128,K[w++]=W&63|128;U=w-N-L}else U=G(Y,N+L);if(U<32)K[N++]=160|U;else if(U<256){if(L<2)K.copyWithin(N+2,N+1,N+1+U);K[N++]=217,K[N++]=U}else if(U<65536){if(L<3)K.copyWithin(N+3,N+2,N+2+U);K[N++]=218,K[N++]=U>>8,K[N++]=U&255}else{if(L<5)K.copyWithin(N+5,N+3,N+3+U);K[N++]=219,I.setUint32(N,U),N+=4}N+=U}else if(A==="number")if(Y>>>0===Y)if(Y<32||Y<128&&this.useRecords===!1||Y<64&&!this.randomAccessStructure)K[N++]=Y;else if(Y<256)K[N++]=204,K[N++]=Y;else if(Y<65536)K[N++]=205,K[N++]=Y>>8,K[N++]=Y&255;else K[N++]=206,I.setUint32(N,Y),N+=4;else if(Y>>0===Y)if(Y>=-32)K[N++]=256+Y;else if(Y>=-128)K[N++]=208,K[N++]=Y+256;else if(Y>=-32768)K[N++]=209,I.setInt16(N,Y),N+=2;else K[N++]=210,I.setInt32(N,Y),N+=4;else{let F;if((F=this.useFloat32)>0&&Y<4294967296&&Y>=-2147483648){K[N++]=202,I.setFloat32(N,Y);let L;if(F<4||(L=Y*S8[(K[N]&127)<<1|K[N+1]>>7])>>0===L){N+=4;return}else N--}K[N++]=203,I.setFloat64(N,Y),N+=8}else if(A==="object"||A==="function")if(!Y)K[N++]=192;else{if(q){let L=q.get(Y);if(L){if(!L.id){let R=q.idsToInsert||(q.idsToInsert=[]);L.id=R.push(L)}K[N++]=214,K[N++]=112,I.setUint32(N,L.id),N+=4;return}else q.set(Y,{offset:N-Q})}let F=Y.constructor;if(F===Object)P8(Y);else if(F===Array)a8(Y);else if(F===Map)if(this.mapAsEmptyObject)K[N++]=128;else{if(U=Y.size,U<16)K[N++]=128|U;else if(U<65536)K[N++]=222,K[N++]=U>>8,K[N++]=U&255;else K[N++]=223,I.setUint32(N,U),N+=4;for(let[L,R]of Y)y(L),y(R)}else{for(let L=0,R=g8.length;L<R;L++){let B=f8[L];if(Y instanceof B){let W=g8[L];if(W.write){if(W.type)K[N++]=212,K[N++]=W.type,K[N++]=0;let O8=W.write.call(this,Y);if(O8===Y)if(Array.isArray(Y))a8(Y);else P8(Y);else y(O8);return}let x=K,w=I,t=N;K=null;let q8;try{q8=W.pack.call(this,Y,(O8)=>{if(K=x,x=null,N+=O8,N>d)Z8(N);return{target:K,targetView:I,position:N-O8}},y)}finally{if(x)K=x,I=w,N=t,d=K.length-10}if(q8){if(q8.length+N>d)Z8(q8.length+N);N=F0(q8,K,N,W.type)}return}}if(Array.isArray(Y))a8(Y);else{if(Y.toJSON){let L=Y.toJSON();if(L!==Y)return y(L)}if(A==="function")return y(this.writeFunction&&this.writeFunction(Y));P8(Y)}}}else if(A==="boolean")K[N++]=Y?195:194;else if(A==="bigint"){if(Y<9223372036854776000&&Y>=-9223372036854776000)K[N++]=211,I.setBigInt64(N,Y);else if(Y<18446744073709552000&&Y>0)K[N++]=207,I.setBigUint64(N,Y);else if(this.largeBigIntToFloat)K[N++]=203,I.setFloat64(N,Number(Y));else if(this.largeBigIntToString)return y(Y.toString());else if(this.useBigIntExtension||this.moreTypes){let F=Y<0?BigInt(-1):BigInt(0),L;if(Y>>BigInt(65536)===F){let R=BigInt(18446744073709552000)-BigInt(1),B=[];while(!0){if(B.push(Y&R),Y>>BigInt(63)===F)break;Y>>=BigInt(64)}L=new Uint8Array(new BigUint64Array(B).buffer),L.reverse()}else{let R=Y<0,B=(R?~Y:Y).toString(16);if(B.length%2)B="0"+B;else if(parseInt(B.charAt(0),16)>=8)B="00"+B;if(D8)L=Buffer.from(B,"hex");else{L=new Uint8Array(B.length/2);for(let W=0;W<L.length;W++)L[W]=parseInt(B.slice(W*2,W*2+2),16)}if(R)for(let W=0;W<L.length;W++)L[W]=~L[W]}if(L.length+N>d)Z8(L.length+N);N=F0(L,K,N,66);return}else throw RangeError(Y+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");N+=8}else if(A==="undefined")if(this.encodeUndefinedAsNil)K[N++]=192;else K[N++]=212,K[N++]=0,K[N++]=0;else throw Error("Unknown type: "+A)},yX=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(Y)=>{let A;if(this.skipValues){A=[];for(let L in Y)if((typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(L))&&!this.skipValues.includes(Y[L]))A.push(L)}else A=Object.keys(Y);let U=A.length;if(U<16)K[N++]=128|U;else if(U<65536)K[N++]=222,K[N++]=U>>8,K[N++]=U&255;else K[N++]=223,I.setUint32(N,U),N+=4;let F;if(this.coercibleKeyAsNumber)for(let L=0;L<U;L++){F=A[L];let R=Number(F);y(isNaN(R)?F:R),y(Y[F])}else for(let L=0;L<U;L++)y(F=A[L]),y(Y[F])}:(Y)=>{K[N++]=222;let A=N-Q;N+=2;let U=0;for(let F in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(F))y(F),y(Y[F]),U++;if(U>65535)throw Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');K[A+++Q]=U>>8,K[A+Q]=U&255},SX=this.useRecords===!1?yX:X.progressiveRecords&&!j?(Y)=>{let A,U=H.transitions||(H.transitions=Object.create(null)),F=N++-Q,L;for(let R in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(R)){if(A=U[R],A)U=A;else{let B=Object.keys(Y),W=U;U=H.transitions;let x=0;for(let w=0,t=B.length;w<t;w++){let q8=B[w];if(A=U[q8],!A)A=U[q8]=Object.create(null),x++;U=A}if(F+Q+1==N)N--,r8(U,B,x);else hX(U,B,F,x);L=!0,U=W[R]}y(Y[R])}if(!L){let R=U[Y8];if(R)K[F+Q]=R;else hX(U,Object.keys(Y),F,0)}}:(Y)=>{let A,U=H.transitions||(H.transitions=Object.create(null)),F=0;for(let R in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(R)){if(A=U[R],!A)A=U[R]=Object.create(null),F++;U=A}let L=U[Y8];if(L)if(L>=96&&j)K[N++]=((L-=96)&31)+96,K[N++]=L>>5;else K[N++]=L;else r8(U,U.__keys__||Object.keys(Y),F);for(let R in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(R))y(Y[R])},vX=typeof this.useRecords=="function"&&this.useRecords,P8=vX?(Y)=>{vX(Y)?SX(Y):yX(Y)}:SX,Z8=(Y)=>{let A;if(Y>16777216){if(Y-Q>D0)throw Error("Packed buffer would be larger than maximum buffer size");A=Math.min(D0,Math.round(Math.max((Y-Q)*(Y>67108864?1.25:2),4194304)/4096)*4096)}else A=(Math.max(Y-Q<<2,K.length-1)>>12)+1<<12;let U=new h8(A);if(I=U.dataView||(U.dataView=new DataView(U.buffer,0,A)),Y=Math.min(Y,K.length),K.copy)K.copy(U,0,Q,Y);else U.set(K.slice(Q,Y));return N-=Q,Q=0,d=U.length-10,K=U},r8=(Y,A,U)=>{let F=H.nextId;if(!F)F=64;if(F<k&&this.shouldShareStructure&&!this.shouldShareStructure(A)){if(F=H.nextOwnId,!(F<v))F=k;H.nextOwnId=F+1}else{if(F>=v)F=k;H.nextId=F+1}let L=A.highByte=F>=96&&j?F-96>>5:-1;if(Y[Y8]=F,Y.__keys__=A,H[F-64]=A,F<k)if(A.isShared=!0,H.sharedLength=F-63,Z=!0,L>=0)K[N++]=(F&31)+96,K[N++]=L;else K[N++]=F;else{if(L>=0)K[N++]=213,K[N++]=114,K[N++]=(F&31)+96,K[N++]=L;else K[N++]=212,K[N++]=114,K[N++]=F;if(U)g+=Q8*U;if(u.length>=V)u.shift()[Y8]=0;u.push(Y),y(A)}},hX=(Y,A,U,F)=>{let L=K,R=N,B=d,W=Q;if(K=A8,N=0,Q=0,!K)A8=K=new h8(8192);d=K.length-10,r8(Y,A,F),A8=K;let x=N;if(K=L,N=R,d=B,Q=W,x>1){let w=N+x-1;if(w>d)Z8(w);let t=U+Q;K.copyWithin(t+x,t+1,N),K.set(A8.slice(0,x),t),N=w}else K[U+Q]=A8[0]},mX=(Y)=>{let A=c0(Y,K,Q,N,H,Z8,(U,F,L)=>{if(L)return Z=!0;N=F;let R=K;if(y(U),T8(),R!==K)return{position:N,targetView:I,target:K};return N},this);if(A===0)return P8(Y);N=A}}useBuffer(X){K=X,K.dataView||(K.dataView=new DataView(K.buffer,K.byteOffset,K.byteLength)),I=K.dataView,N=0}set position(X){N=X}get position(){return N}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}f8=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,y8];g8=[{pack(X,$,Q){let Z=X.getTime()/1000;if((this.useTimestamp32||X.getMilliseconds()===0)&&Z>=0&&Z<4294967296){let{target:H,targetView:q,position:G}=$(6);H[G++]=214,H[G++]=255,q.setUint32(G,Z)}else if(Z>0&&Z<4294967296){let{target:H,targetView:q,position:G}=$(10);H[G++]=215,H[G++]=255,q.setUint32(G,X.getMilliseconds()*4000000+(Z/1000/4294967296>>0)),q.setUint32(G+4,Z)}else if(isNaN(Z)){if(this.onInvalidDate)return $(0),Q(this.onInvalidDate());let{target:H,targetView:q,position:G}=$(3);H[G++]=212,H[G++]=255,H[G++]=255}else{let{target:H,targetView:q,position:G}=$(15);H[G++]=199,H[G++]=12,H[G++]=255,q.setUint32(G,X.getMilliseconds()*1e6),q.setBigInt64(G+4,BigInt(Math.floor(Z)))}}},{pack(X,$,Q){if(this.setAsEmptyObject)return $(0),Q({});let Z=Array.from(X),{target:H,position:q}=$(this.moreTypes?3:0);if(this.moreTypes)H[q++]=212,H[q++]=115,H[q++]=0;Q(Z)}},{pack(X,$,Q){let{target:Z,position:H}=$(this.moreTypes?3:0);if(this.moreTypes)Z[H++]=212,Z[H++]=101,Z[H++]=0;Q([X.name,X.message,X.cause])}},{pack(X,$,Q){let{target:Z,position:H}=$(this.moreTypes?3:0);if(this.moreTypes)Z[H++]=212,Z[H++]=120,Z[H++]=0;Q([X.source,X.flags])}},{pack(X,$){if(this.moreTypes)KX(X,16,$);else YX(D8?Buffer.from(X):new Uint8Array(X),$)}},{pack(X,$){let Q=X.constructor;if(Q!==O0&&this.moreTypes)KX(X,GX.indexOf(Q.name),$);else YX(X,$)}},{pack(X,$){if(this.moreTypes)KX(X,17,$);else YX(D8?Buffer.from(X):new Uint8Array(X),$)}},{pack(X,$){let{target:Q,position:Z}=$(1);Q[Z]=193}}];function KX(X,$,Q,Z){let H=X.byteLength;if(H+1<256){var{target:q,position:G}=Q(4+H);q[G++]=199,q[G++]=H+1}else if(H+1<65536){var{target:q,position:G}=Q(5+H);q[G++]=200,q[G++]=H+1>>8,q[G++]=H+1&255}else{var{target:q,position:G,targetView:D}=Q(7+H);q[G++]=201,D.setUint32(G,H+1),G+=4}if(q[G++]=116,q[G++]=$,!X.buffer)X=new Uint8Array(X);q.set(new Uint8Array(X.buffer,X.byteOffset,X.byteLength),G)}function YX(X,$){let Q=X.byteLength;var Z,H;if(Q<256){var{target:Z,position:H}=$(Q+2);Z[H++]=196,Z[H++]=Q}else if(Q<65536){var{target:Z,position:H}=$(Q+3);Z[H++]=197,Z[H++]=Q>>8,Z[H++]=Q&255}else{var{target:Z,position:H,targetView:q}=$(Q+5);Z[H++]=198,q.setUint32(H,Q),H+=4}Z.set(X,H)}function F0(X,$,Q,Z){let H=X.length;switch(H){case 1:$[Q++]=212;break;case 2:$[Q++]=213;break;case 4:$[Q++]=214;break;case 8:$[Q++]=215;break;case 16:$[Q++]=216;break;default:if(H<256)$[Q++]=199,$[Q++]=H;else if(H<65536)$[Q++]=200,$[Q++]=H>>8,$[Q++]=H&255;else $[Q++]=201,$[Q++]=H>>24,$[Q++]=H>>16&255,$[Q++]=H>>8&255,$[Q++]=H&255}return $[Q++]=Z,$.set(X,Q),Q+=H,Q}function s0(X,$){let Q,Z=$.length*6,H=X.length-Z;while(Q=$.pop()){let{offset:q,id:G}=Q;X.copyWithin(q+Z,q,H),Z-=6;let D=q+Z;X[D++]=214,X[D++]=105,X[D++]=G>>24,X[D++]=G>>16&255,X[D++]=G>>8&255,X[D++]=G&255,H=q}return X}function L0(X,$,Q){if(S.length>0){I.setUint32(S.position+X,N+Q-S.position-X),S.stringsPosition=N-X;let Z=S;S=null,$(Z[0]),$(Z[1])}}function DX(X){if(X.Class){if(!X.pack&&!X.write)throw Error("Extension has no pack or write function");if(X.pack&&!X.type)throw Error("Extension has no type (numeric code to identify the extension)");f8.unshift(X.Class),g8.unshift(X)}Y0(X)}function i0(X,$){return X.isCompatible=(Q)=>{let Z=!Q||($.lastNamedStructuresLength||0)===Q.length;if(!Z)$._mergeStructures(Q);return Z},X}var _0=new F8({useRecords:!1}),a0=_0.pack,r0=_0.pack;var A0=512,z0=1024,M0=2048;var R0=80;class a{capId;constructor(X){this.capId=X}}var t0=new Set(["hello","goaway","call","result","cancel","stream","drop","cap_revoked"]);function FX(X){if(typeof X!=="object"||X===null)return!1;let $=X,Q=$.op;if(typeof Q!=="string"||!t0.has(Q))return!1;switch(Q){case"hello":return $.v===1&&($.mode==="native"||$.mode==="web")&&Array.isArray($.features)&&typeof $.maxBytes==="number"&&typeof $.origin==="string";case"goaway":return $.reason===void 0||typeof $.reason==="string";case"call":return typeof $.id==="number"&&typeof $.method==="string"&&typeof $.target==="object"&&$.target!==null&&$.target.kind==="cap"&&typeof $.target.id==="number";case"result":return typeof $.id==="number"&&($.ok===!0||$.ok===!1);case"cancel":return typeof $.id==="number";case"stream":return typeof $.id==="number"&&typeof $.ev==="string"&&($.ev==="next"||$.ev==="credit"||$.ev==="end"||$.ev==="error");case"drop":return Array.isArray($.caps);case"cap_revoked":if(!Array.isArray($.capIds))return!1;for(let Z of $.capIds)if(typeof Z!=="number"||!Number.isInteger(Z)||Z<0||Z>4294967295)return!1;return!0}}var W0=!1;function e0(){if(W0)return;W0=!0,DX({Class:a,type:R0,pack:(X)=>X$(X.capId),unpack:(X)=>new a(Q$(X))})}function LX(){return e0(),{packr:new F8({useRecords:!0,sequential:!0,moreTypes:!0}),unpackr:new X8({useRecords:!0,sequential:!0,moreTypes:!0})}}function X$(X){let $=new Uint8Array(5),Q=X>>>0,Z=0;while(Q>=128)$[Z++]=Q&127|128,Q>>>=7;return $[Z++]=Q&127,$.subarray(0,Z)}var $$=5;function Q$(X){let $=0,Q=0,Z=Math.min(X.length,$$);for(let H=0;H<Z;H++){let q=X[H];if($|=(q&127)<<Q,(q&128)===0)return $>>>0;Q+=7}throw Error("Truncated or oversize varuint")}var UX=67108864,OX=1,p8="bunite.",u8="bootstrap";class P extends Error{code;details;retry;constructor(X){super(X.message??X.code);this.name="IpcError",this.code=X.code,this.details=X.details,this.retry=X.retry}toStatus(){return{code:this.code,message:this.message,details:this.details,retry:this.retry}}}var l8=i("bunite.BrowserWindow",{focus:z(),close:z(),setBounds:z(),setTitle:z(),id:z({idempotent:!0}),label:z({idempotent:!0})}),_X=i("bunite.Window",{create:z({returns:n(l8)}),list:z({returns:n.array(l8),idempotent:!0}),focus:z(),close:z()}),d8=i("bunite.FileRef",{text:z({idempotent:!0}),bytes:z({idempotent:!0}),path:z({idempotent:!0}),revoke:z()},{disposal:{method:"revoke"}}),AX=i("bunite.Dialogs",{openFile:z({returns:n.array(d8)}),saveFile:z({returns:n(d8)}),showMessage:z()}),zX=i("bunite.Clipboard",{readText:z({idempotent:!0}),writeText:z(),readBytes:z({idempotent:!0}),writeBytes:z()}),MX=i("bunite.Shell",{openExternal:z(),showItemInFolder:z()}),WX=i("bunite.PageReporting",{reportConsoleBatch:z()}),RX=i("bunite.Surface",{init:z(),resize:z(),remove:z(),setHidden:z(),setMasks:z(),setAllPassthrough:z(),bringAllVisiblesToFront:z(),navigate:z(),goBack:z(),reload:z(),evaluate:z(),capabilities:z(),click:z(),type:z(),press:z(),scroll:z(),mouse:z(),screenshot:z(),waitForSelector:z(),waitForFunction:z(),respondToDialog:z(),setDialogTimeout:z(),getConsoleBuffer:z({idempotent:!0}),surfaceEvents:G8(),dialogs:G8(),consoleEvents:G8(),getNavigationState:z({idempotent:!0}),accessibilitySnapshot:z(),getBoundingRect:z({idempotent:!0}),listFrames:z({idempotent:!0}),downloadEvents:G8(),waitForDownload:z(),setDownloadPolicy:z(),acceptPopup:z(),dismissPopup:z(),extendPopupTimeout:z(),resolveAndClick:z()}),z8=i("bunite.Runtime",{window:z({returns:n(_X),idempotent:!0}),dialogs:z({returns:n(AX),idempotent:!0}),clipboard:z({returns:n(zX),idempotent:!0}),shell:z({returns:n(MX),idempotent:!0}),appName:z({idempotent:!0}),appVersion:z({idempotent:!0}),theme:z({idempotent:!0}),themeWatch:G8(),surface:z({returns:n(RX),idempotent:!0}),reporting:z({returns:n(WX),idempotent:!0}),popupMetrics:z({idempotent:!0})}),$8={Runtime:1,Window:2,Dialogs:3,FileRef:4,Clipboard:5,Shell:6,BrowserWindow:7,Surface:8,PageReporting:9},Z$=new Map([[z8,$8.Runtime],[_X,$8.Window],[AX,$8.Dialogs],[d8,$8.FileRef],[zX,$8.Clipboard],[MX,$8.Shell],[l8,$8.BrowserWindow],[RX,$8.Surface],[WX,$8.PageReporting]]);function BX(X){return Z$.get(X)}var n8=0,PX=1,V0=0,T0=1,L8=2,CX=128,o8=1024,P0=1024,H$=o8*4,q$=500,J$=32,N$=8,G$=1024;function K$(X){let $=X?.initialBudget;if(typeof $!=="number"||!Number.isFinite($)||!Number.isInteger($)||$<1)return J$;return Math.min($,G$)}var c8=null;class EX{entries=new Map;nextCapId=L8;capLimit;constructor(X=o8){this.capLimit=X}install(X,$){if(this.entries.has(X))throw Error(`cap-id ${X} already installed`);let Q={capId:X,...$};return this.entries.set(X,Q),Q}allocate(X){if(this.entries.size>=this.capLimit)throw new P({code:"resource_exhausted",message:`cap-table limit ${this.capLimit}`,details:{reason:"max_caps_per_connection"}});let $=this.nextCapId++;while(this.entries.has($))$=this.nextCapId++;return this.install($,X)}get(X){return this.entries.get(X)}release(X,$=1){let Q=this.entries.get(X);if(!Q)return!1;if(Q.refCount=Math.max(0,Q.refCount-$),Q.refCount===0&&X>=L8)return this.entries.delete(X),!0;return!1}delete(X){if(X<L8)return!1;return this.entries.delete(X)}clear(){this.entries.clear(),this.nextCapId=L8}size(){return this.entries.size}values(){return this.entries.values()}}var Y$={origin:"",topOrigin:"",partition:"default",isAppRes:!1,isMainFrame:!1,userGesture:!1,level:"untrusted"},C0=Symbol("bunite.rpc.ExportedCap"),B0=Symbol("bunite.rpc.CapProxyMeta");function D$(X){return typeof X==="object"&&X!==null&&X[C0]===!0}var F$=typeof FinalizationRegistry<"u"?new FinalizationRegistry((X)=>{if(X.dropped())return;let $=X.connRef.deref();if(!$||$.closed)return;$._dropFromFinalizer(X.capId)}):{register:()=>{}};class E0{transport;capTable;pending=new Map;clientStreams=new Map;serverStreams=new Map;serverCallChildren=new Map;serverActiveCalls=new Map;registry=new Map;rootInstances=new Map;revokedCapIds=new Set;closeHandlers=new Set;observers={};nextCallId=1;remoteHello=null;remoteReady;resolveRemoteReady;rejectRemoteReady;closed_=!1;maxBytes;maxInFlightCalls;mode;origin;features;attestation;peerId;policy;constructor(X){this.transport=X.transport,this.mode=X.mode,this.origin=X.origin,this.features=X.features??[],this.maxBytes=X.maxBytes??UX,this.maxInFlightCalls=X.maxInFlightCalls??P0,this.attestation=X.attestation??Y$,this.peerId=X.peerId??"peer",this.policy=X.policy,this.capTable=new EX(X.capLimit??o8),this.capTable.install(n8,{typeId:V0,cap:null,impl:null,refCount:1}),this.capTable.install(PX,{typeId:T0,cap:z8,impl:X.runtime??null,refCount:1}),this.remoteReady=new Promise(($,Q)=>{this.resolveRemoteReady=$,this.rejectRemoteReady=Q}),this.remoteReady.catch(()=>{}),this.transport.setReceive(($)=>this.handleFrame($)),this.transport.send({op:"hello",v:OX,mode:this.mode,features:this.features,maxBytes:this.maxBytes,origin:this.origin})}get closed(){return this.closed_}onClose(X){return this.closeHandlers.add(X),()=>this.closeHandlers.delete(X)}on(X,$){let Q=this.observers[X];if(!Q)Q=new Set,this.observers[X]=Q;return Q.add($),()=>{Q.delete($)}}emitObs(X,$){let Q=this.observers[X];if(!Q||Q.size===0)return;for(let Z of Q)try{Z($)}catch{}}markRevoked(X){this.revokedCapIds.add(X);while(this.revokedCapIds.size>H$){let $=this.revokedCapIds.values().next().value;if($===void 0)break;this.revokedCapIds.delete($)}}serve(X,$,Q){this.assertNotFrameworkName(X.name);let Z=Q?.ifExists??"throw";if(this.registry.get(X.name))switch(Z){case"throw":throw new P({code:"already_exists",message:`cap "${X.name}" already served`,details:{reason:"name_collision"}});case"skip":return this.makeHandle([]);case"replace":return this.replace(X,$),this.makeHandle([X.name])}return this.registry.set(X.name,{cap:X,impl:$,version:X.version}),this.makeHandle([X.name])}makeHandle(X){let $={names:X,[Symbol.dispose]:()=>this.unserve($)};return $}serveAll(X,$,Q){let Z=Q?.ifExists??"throw";for(let q of Object.keys(X.roots)){let G=X.roots[q];this.assertNotFrameworkName(G.name);let D=this.registry.get(G.name);if(D){if(Z==="throw")throw new P({code:"already_exists",message:`cap "${G.name}" already served`,details:{reason:"name_collision"}});if(Z==="replace"&&D.version!==G.version)throw new P({code:"failed_precondition",message:`version mismatch on replace for "${G.name}" (current "${D.version}", new "${G.version}")`,details:{reason:"version_mismatch"}})}}let H=[];for(let q of Object.keys(X.roots)){let G=X.roots[q],D=$[q];if(this.serve(G,D,{ifExists:Z}).names.length>0)H.push(G.name)}return this.makeHandle(H)}unserve(X){let $=b8(X)?[X.name]:Array.from(X.names),Q=[];for(let Z of $){if(!this.registry.delete(Z))continue;let H=this.rootInstances.get(Z);if(H!==void 0){let q=this.capTable.get(H);if(q)this.invokeServerDisposal(q);this.rootInstances.delete(Z),this.capTable.delete(H),Q.push(H)}}if(Q.length>0)this.transport.send({op:"cap_revoked",capIds:Q}),this.emitObs("revoke",{capIds:Q,reason:"unserve"})}replace(X,$){let Q=this.registry.get(X.name);if(!Q)throw new P({code:"not_found",message:`cap "${X.name}" not served`});if(Q.version!==X.version)throw new P({code:"failed_precondition",message:`version mismatch (current "${Q.version}", new "${X.version}")`,details:{reason:"version_mismatch"}});Q.impl=$,Q.cap=X;let Z=this.rootInstances.get(X.name);if(Z!==void 0){let H=this.capTable.get(Z);if(H)H.impl=$,H.cap=X}this.emitObs("revoke",{capIds:Z!==void 0?[Z]:[],reason:"replace"})}assertNotFrameworkName(X){if(X.startsWith(p8))throw new P({code:"already_exists",message:`cap name "${X}" uses reserved prefix "${p8}"`,details:{reason:"reserved_namespace"}})}runtimeProxy=null;runtime(){if(!this.runtimeProxy)this.runtimeProxy=this.makeCapProxy(z8,PX);return this.runtimeProxy}async bootstrap(X){if(b8(X))return this._bootstrapCap(X);if(e8(X))return this._bootstrapSchema(X);throw new P({code:"invalid_argument",message:"bootstrap target must be CapDef or Schema"})}async _bootstrapCap(X){await this.remoteReady;let $={name:X.name};if(X.version!=null)$.version=X.version;let Q=await this.sendCallTyped(n8,u8,$,void 0);if(!(Q instanceof a))throw new P({code:"invalid_argument",message:"bootstrap did not return a CapRef"});return this.makeCapProxy(X,Q.capId)}async _bootstrapSchema(X){let $=Object.keys(X.roots),Q=await Promise.allSettled($.map((q)=>this._bootstrapCap(X.roots[q]))),Z=Q.find((q)=>q.status==="rejected");if(Z){for(let q of Q)if(q.status==="fulfilled")try{this.releaseRef(q.value)}catch{}throw Z.reason}let H={};for(let q=0;q<$.length;q++)H[$[q]]=Q[q].value;return H}handleFrame(X){if(this.closed_)return;switch(X.op){case"hello":this.handleHello(X);return;case"call":this.handleCall(X);return;case"result":this.handleResult(X);return;case"cancel":this.handleCancel(X);return;case"stream":this.handleStreamFrame(X);return;case"drop":this.handleDrop(X);return;case"cap_revoked":this.handleCapRevoked(X);return;case"goaway":this.handleGoaway(X);return;default:this.handleUnknownFrame(X);return}}handleUnknownFrame(X){let $=X?.id;if(typeof $==="number"){this.transport.send({op:"result",id:$,ok:!1,error:{code:"invalid_argument",message:"unknown opcode"}});return}this.transport.send({op:"goaway",reason:"invalid_argument",error:{code:"invalid_argument",message:"unknown opcode"}}),this.shutdown("invalid_argument")}handleHello(X){this.remoteHello=X,this.resolveRemoteReady(X)}handleGoaway(X){this.rejectRemoteReady(new P(X.error??{code:"unavailable",message:X.reason??"peer goaway"})),this.shutdown(X.reason??"remote goaway")}handleCapRevoked(X){for(let $ of X.capIds){this.markRevoked($);let Q=new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}});for(let[Z,H]of this.pending)if(H.capId===$){if(this.pending.delete(Z),H.timer)clearTimeout(H.timer);H.reject(Q)}for(let[Z,H]of this.clientStreams)if(H.capId===$)this.clientStreams.delete(Z),H.fail(Q)}}async handleCall(X){if(X.target.id===n8&&X.method===u8){await this.handleBootstrap(X);return}let $=this.capTable.get(X.target.id);if(!$)return this.emitObs("call",{capId:X.target.id,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found",`cap-id ${X.target.id} not found`);let Q=$.cap;if(!Q||!$.impl)return this.emitObs("call",{capId:X.target.id,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found","cap has no impl");let Z=Q.methods[X.method];if(!Z)return this.emitObs("call",{capId:X.target.id,capName:Q.name,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found",`method "${X.method}" on cap "${Q.name}"`);let H=$.impl[X.method];if(typeof H!=="function")return this.emitObs("call",{capId:X.target.id,capName:Q.name,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found",`method "${X.method}" has no handler`);if(this.serverActiveCalls.size+this.serverStreams.size>=this.maxInFlightCalls)return this.emitObs("call",{capId:X.target.id,capName:Q.name,method:X.method,callId:X.id,result:"resource_exhausted"}),this.sendError(X.id,"resource_exhausted",`in-flight calls limit ${this.maxInFlightCalls}`,{reason:"max_concurrent_calls"});await this.invokeServerMethod(X,Q,Z,H)}async handleBootstrap(X){let $=X.args??{},Q=$.name;if(typeof Q!=="string")return this.emitObs("bootstrap",{name:String(Q),attestation:this.attestation,result:"invalid_argument"}),this.sendError(X.id,"invalid_argument","bootstrap requires {name: string}");let Z=$.version!=null?String($.version):void 0,H=this.registry.get(Q);if(!H)return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"not_found"}),this.sendError(X.id,"not_found",`cap "${Q}" not served`);let q=H.version;if(q!=null&&Z!=null&&q!==Z)return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"version_mismatch"}),this.sendError(X.id,"failed_precondition",`version mismatch (server "${q}", client "${Z}")`,{reason:"version_mismatch"});if(this.policy){let D;try{D=await this.policy(Q,this.attestation)}catch(O){return this.emitObs("error",{phase:"policy",error:O instanceof Error?O:Error(String(O))}),this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"internal"}),this.sendError(X.id,"internal","policy threw")}if(typeof D!=="boolean")return this.emitObs("error",{phase:"policy",error:Error(`policy must return boolean (got ${typeof D})`)}),this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"internal"}),this.sendError(X.id,"internal","policy returned non-boolean");if(!D)return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"denied"}),this.sendError(X.id,"failed_precondition","policy denied",{reason:"unauthorized"})}let G=this.rootInstances.get(Q);if(G!==void 0){let D=this.capTable.get(G);if(D)D.refCount+=1;else this.rootInstances.delete(Q),G=void 0}if(G===void 0)try{G=this.capTable.allocate({typeId:BX(H.cap)??CX,cap:H.cap,impl:H.impl,refCount:1}).capId,this.rootInstances.set(Q,G)}catch(D){if(D instanceof P){let O=D.code==="resource_exhausted"?"resource_exhausted":"internal";return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:O}),this.sendError(X.id,D.code,D.message,D.details)}throw D}this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"ok",capId:G}),this.transport.send({op:"result",id:X.id,ok:!0,value:new a(G)})}async invokeServerMethod(X,$,Q,Z){let H=this.makeCallCtx(X);if(w8(Q)){let q=K$(Q.hint);try{let G=()=>Z(X.args,H),D=c8,M=(D?()=>D.run({callId:X.id},G):G)();this.runServerStream(X.id,M,H,q,$,X.method,X.target.id)}catch(G){this.emitObs("stream",{capId:X.target.id,capName:$.name,method:X.method,callId:X.id,event:"error"}),this.transport.send({op:"stream",id:X.id,ev:"error",error:VX(G)})}return}if(x8(Q)){let q=performance.now(),G=Q.idempotent?void 0:this.armServerDeadline(X,H);this.serverActiveCalls.set(X.id,{ctrl:H._ctrl,capId:X.target.id,capName:$.name,method:X.method,startedAt:q});let D=L$(Q.returns),O=()=>Promise.resolve(Z(X.args,H)),M=c8,T=M?()=>M.run({callId:X.id},O):O;try{let V=await T();if(G)clearTimeout(G);if(!this.serverActiveCalls.delete(X.id))return;let j=D(V);this.transport.send({op:"result",id:X.id,ok:!0,value:j}),this.emitObs("call",{capId:X.target.id,capName:$.name,method:X.method,callId:X.id,durationMs:performance.now()-q,result:"ok"})}catch(V){if(G)clearTimeout(G);if(!this.serverActiveCalls.delete(X.id))return;let j=VX(V);this.sendErrorFromStatus(X.id,j),this.emitObs("call",{capId:X.target.id,capName:$.name,method:X.method,callId:X.id,durationMs:performance.now()-q,result:j.code})}return}this.sendError(X.id,"not_found","unknown method kind")}armServerDeadline(X,$){let Q=X.meta?.deadlineMs;if(!Q)return;return setTimeout(()=>{$._ctrl.abort()},Q)}makeCallCtx(X){let $=new AbortController;return{callId:X.id,peerId:this.peerId,attestation:this.attestation,signal:$.signal,deadline:X.meta?.deadlineMs,_ctrl:$,exportCap:(Z,H)=>this.exportCap(Z,H)}}exportCap(X,$){let Q=BX(X)??CX,Z=this.capTable.allocate({typeId:Q,cap:X,impl:$,refCount:1});return{[C0]:!0,cap:X,capId:Z.capId,typeId:Z.typeId}}runServerStream(X,$,Q,Z,H,q,G){let D=$[Symbol.asyncIterator](),O=Q._ctrl,M={iter:D,abort:O,cancelled:!1,credit:Z,creditWaker:null,capId:G,capName:H.name,method:q,callId:X,count:0};this.serverStreams.set(X,M),this.emitObs("stream",{capId:G,capName:H.name,method:q,callId:X,event:"start"});let T=()=>{if(M.credit>0||M.cancelled)return Promise.resolve();return new Promise((j)=>{M.creditWaker=j})};(async()=>{let j=!1;try{while(!M.cancelled){if(M.credit===0)await T();if(M.cancelled)break;let{done:k,value:v}=await D.next();if(k)break;if(M.cancelled)break;M.credit-=1,M.count+=1,this.transport.send({op:"stream",id:X,ev:"next",value:v})}}catch(k){j=!0,this.transport.send({op:"stream",id:X,ev:"error",error:VX(k)}),this.emitObs("stream",{capId:G,capName:H.name,method:q,callId:X,event:"error",count:M.count})}finally{if(!j)this.transport.send({op:"stream",id:X,ev:"end"}),this.emitObs("stream",{capId:G,capName:H.name,method:q,callId:X,event:M.cancelled?"cancel":"end",count:M.count});this.serverStreams.delete(X)}})()}handleResult(X){let $=this.pending.get(X.id);if($){if(this.pending.delete(X.id),this.serverCallChildren.delete(X.id),$.timer)clearTimeout($.timer);if(X.ok){let Z=$.decodeReturn?$.decodeReturn(X.value):X.value;$.resolve(Z)}else $.reject(new P(X.error));return}let Q=this.clientStreams.get(X.id);if(Q){this.clientStreams.delete(X.id);let Z=X.ok?new P({code:"invalid_argument",message:"stream method returned result frame"}):new P(X.error);Q.fail(Z)}}handleCancel(X){let $=this.serverStreams.get(X.id);if($)$.cancelled=!0,$.abort.abort(),$.iter?.return?.(),this.serverStreams.delete(X.id);let Q=this.serverActiveCalls.get(X.id);if(Q)this.serverActiveCalls.delete(X.id),Q.ctrl.abort(),this.transport.send({op:"result",id:X.id,ok:!1,error:{code:"cancelled",message:X.reason}}),this.emitObs("call",{capId:Q.capId,capName:Q.capName,method:Q.method,callId:X.id,durationMs:performance.now()-Q.startedAt,result:"cancelled"});for(let[Z,H]of this.serverCallChildren){if(H.parentId!==X.id)continue;if(this.serverCallChildren.delete(Z),this.pending.has(Z))this.transport.send({op:"cancel",id:Z,reason:X.reason})}}releaseRef(X){if(typeof X!=="object"||X===null)return;let $=X[B0];if(!$||$.dropped)return;$.dropped=!0,this.sendDrop($.capId)}sendDrop(X){if(this.closed_)return;if(X<L8)return;this.transport.send({op:"drop",caps:[{id:X,delta:1}]})}handleStreamFrame(X){if(X.ev==="credit"){let Q=this.serverStreams.get(X.id);if(!Q)return;Q.credit+=X.credit?.messages??0;let Z=Q.creditWaker;Q.creditWaker=null,Z?.();return}let $=this.clientStreams.get(X.id);if(!$)return;switch(X.ev){case"next":$.push(X.value);return;case"end":$.end(),this.clientStreams.delete(X.id);return;case"error":$.fail(new P(X.error)),this.clientStreams.delete(X.id);return}}handleDrop(X){for(let{id:$,delta:Q}of X.caps)if(this.capTable.release($,Q)){for(let[H,q]of this.rootInstances)if(q===$){this.rootInstances.delete(H);break}}}sendError(X,$,Q,Z){let H={code:$,message:Q};if(Z!==void 0)H.details=Z;this.transport.send({op:"result",id:X,ok:!1,error:H})}sendErrorFromStatus(X,$){this.transport.send({op:"result",id:X,ok:!1,error:$})}nextId(){return this.nextCallId++}sendCallTyped(X,$,Q,Z,H,q){if(this.closed_)return Promise.reject(new P({code:"unavailable",message:"connection closed"}));if(this.revokedCapIds.has(X))return Promise.reject(new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}}));if(this.pending.size>=this.maxInFlightCalls)return Promise.reject(new P({code:"resource_exhausted",message:`in-flight calls limit ${this.maxInFlightCalls}`,details:{reason:"max_concurrent_calls"}}));let G=this.nextId();return new Promise((D,O)=>{let M=new AbortController,T={resolve:D,reject:O,abort:M,decodeReturn:Z,startedAt:performance.now(),capId:X,method:$,capName:q,kind:"call"};if(H?.deadlineMs)T.timer=setTimeout(()=>{if(this.pending.delete(G))this.transport.send({op:"cancel",id:G,reason:"deadline_exceeded"}),O(new P({code:"deadline_exceeded"}))},H.deadlineMs+q$);this.pending.set(G,T);let V=H;if(V?.parentCallId===void 0&&c8){let j=c8.getStore();if(j)V={...V??{},parentCallId:j.callId}}if(V?.parentCallId!==void 0)this.serverCallChildren.set(G,{parentId:V.parentCallId});this.transport.send({op:"call",id:G,target:{kind:"cap",id:X},method:$,args:Q,meta:V})})}openClientStream(X,$,Q,Z,H){if(this.closed_){let M=TX(X,0,()=>{},()=>{});return M.fail(new P({code:"unavailable",message:"connection closed"})),M.stream}if(this.revokedCapIds.has(X)){let M=TX(X,0,()=>{},()=>{});return M.fail(new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}})),M.stream}let q=this.nextId(),O=TX(X,q,()=>{if(this.clientStreams.delete(q))this.transport.send({op:"cancel",id:q,reason:"client_cancel"})},(M)=>{if(this.closed_||!this.clientStreams.has(q))return;this.transport.send({op:"stream",id:q,ev:"credit",credit:{messages:M}})});return this.clientStreams.set(q,O),this.transport.send({op:"call",id:q,target:{kind:"cap",id:X},method:$,args:Q,meta:Z}),O.stream}makeCapProxy(X,$){let Q={},Z={capId:$,dropped:!1};Q[B0]=Z;let H=()=>{if(Z.dropped)return;Z.dropped=!0,this.sendDrop($)};for(let G of Object.keys(X.methods)){let D=X.methods[G];if(w8(D))Q[G]=(O)=>this.openClientStream($,G,O,void 0,X.name);else if(x8(D)){let O=U$(D.returns,(M,T)=>this.makeCapProxy(M,T));Q[G]=(M)=>this.sendCallTyped($,G,M,O,void 0,X.name)}}let q=X.disposal;if(q){let G=this;Q[Symbol.dispose]=()=>{try{let D=Q[q.method]?.();if(D&&typeof D.then==="function")D.catch((O)=>G.emitObs("error",{phase:"dispose",error:O instanceof Error?O:Error(String(O))}))}catch(D){G.emitObs("error",{phase:"dispose",error:D instanceof Error?D:Error(String(D))})}H()}}if(typeof FinalizationRegistry<"u")F$.register(Q,{connRef:new WeakRef(this),capId:$,dropped:()=>Z.dropped});return Q}_dropFromFinalizer(X){try{this.sendDrop(X)}catch{}}shutdown(X="shutdown"){if(this.closed_)return;this.closed_=!0;for(let $ of this.pending.values()){if($.timer)clearTimeout($.timer);$.reject(new P({code:"unavailable",message:X}))}this.pending.clear();for(let $ of this.clientStreams.values())$.fail(new P({code:"unavailable",message:X}));this.clientStreams.clear();for(let $ of this.serverStreams.values())$.cancelled=!0,$.abort.abort(),$.iter?.return?.();this.serverStreams.clear();for(let $ of this.serverActiveCalls.values())$.ctrl.abort();this.serverActiveCalls.clear();for(let $ of this.capTable.values())this.invokeServerDisposal($);if(this.capTable.clear(),!this.remoteHello)this.rejectRemoteReady(new P({code:"unavailable",message:X}));for(let $ of this.closeHandlers)try{$()}catch{}this.closeHandlers.clear();try{this.transport.close()}catch{}}invokeServerDisposal(X){let $=X.cap;if(!$)return;let Q=$.disposal;if(!Q)return;let Z=X.impl,H=Z?.[Q.method];if(!H)return;try{H.call(Z,void 0,void 0)}catch{}}}function L$(X){if(!X)return(Q)=>Q;let $=(Q,Z)=>{if(!D$(Q))throw new P({code:"failed_precondition",message:"expected ctx.exportCap return for cap method",details:{reason:"unregistered_cap_return"}});if(Q.cap!==Z)throw new P({code:"failed_precondition",message:"exported cap type mismatch with method returns",details:{reason:"unregistered_cap_return"}});return new a(Q.capId)};if(C8(X))return(Q)=>$(Q,X.cap);if(E8(X))return(Q)=>{if(!Array.isArray(Q))throw new P({code:"invalid_argument",message:"expected ExportedCap[] for cap.array method"});return Q.map((Z)=>$(Z,X.cap))};if(j8(X))return(Q)=>{if(!Q||typeof Q!=="object")throw new P({code:"invalid_argument",message:"expected Record<string, ExportedCap> for cap.record method"});let Z={};for(let H of Object.keys(Q))Z[H]=$(Q[H],X.cap);return Z};return(Q)=>Q}function U$(X,$){if(!X)return;if(C8(X)){let Q=X.cap;return(Z)=>{if(!(Z instanceof a))throw new P({code:"invalid_argument",message:"expected CapRef"});return $(Q,Z.capId)}}if(E8(X)){let Q=X.cap,Z=Q.disposal;return(H)=>{if(!Array.isArray(H))throw new P({code:"invalid_argument",message:"expected array"});let q=H.map((G)=>{if(!(G instanceof a))throw new P({code:"invalid_argument",message:"expected CapRef in array"});return $(Q,G.capId)});return O$(q,Z),q}}if(j8(X)){let Q=X.cap;return(Z)=>{if(!Z||typeof Z!=="object")throw new P({code:"invalid_argument",message:"expected record"});let H={};for(let q of Object.keys(Z)){let G=Z[q];if(!(G instanceof a))throw new P({code:"invalid_argument",message:"expected CapRef in record"});H[q]=$(Q,G.capId)}return H}}return}function O$(X,$){if(!$)return;X[Symbol.dispose]=()=>{for(let Q of X)Q[Symbol.dispose]?.call(Q)}}function VX(X){if(X instanceof P)return X.toStatus();if(X instanceof Error)return{code:"internal",message:X.message};return{code:"internal",message:String(X)}}function TX(X,$,Q,Z){let H=[],q=[],G=!1,D=null,O=!1,M=0;function T(){if(M+=1,M>=N$)Z(M),M=0}function V(){if(H.length>0){let g=H.shift();return T(),{value:g,done:!1}}if(D)return null;if(G||O)return{value:void 0,done:!0};return null}function j(){let g=V();if(g)return Promise.resolve(g);if(D)return Promise.reject(D);return new Promise((Q8,T8)=>q.push({resolve:Q8,reject:T8}))}function k(){while(q.length>0){let g=q.shift(),Q8=V();if(Q8){g.resolve(Q8);continue}if(D){g.reject(D);continue}q.unshift(g);break}}function v(){if(O||G||D)return;O=!0,Q(),k()}let u={[Symbol.asyncIterator]:()=>({next:j,return:()=>{return v(),Promise.resolve({value:void 0,done:!0})},throw:(g)=>{return v(),Promise.reject(g)}}),[Symbol.dispose]:v,cancel:v};return{capId:X,stream:u,push(g){if(O||G||D)return;H.push(g),k()},end(){G=!0,k()},fail(g){D=g,k()}}}function jX(X){return new E0(X)}function xX(X,$={}){let Q=LX(),Z;return X.setReceive((H)=>{let q;try{q=Q.unpackr.unpack(H)}catch(G){$.onProtocolError?.(`unpack failed: ${G instanceof Error?G.message:String(G)}`),X.close();return}if(!FX(q)){$.onProtocolError?.("malformed frame"),X.close();return}Z?.(q)}),{send(H){let q=Q.packr.pack(H);X.send(q instanceof Uint8Array?q:new Uint8Array(q))},setReceive(H){Z=H},close(){X.close()}}}function wX(X){if("binaryType"in X)try{X.binaryType="arraybuffer"}catch{}let $,Q=(Z)=>{if(!$)return;let H=Z.data;if(H instanceof Uint8Array){$(H);return}if(H instanceof ArrayBuffer){$(new Uint8Array(H));return}if(typeof Blob<"u"&&H instanceof Blob){H.arrayBuffer().then((q)=>$?.(new Uint8Array(q)));return}};return X.addEventListener("message",Q),{send(Z){X.send(Z)},setReceive(Z){$=Z},close(){X.removeEventListener?.("message",Q),X.close?.()}}}function M8(X){let $=new ArrayBuffer(X.byteLength);return new Uint8Array($).set(X),$}async function _$(X){return crypto.subtle.importKey("raw",M8(X),"AES-GCM",!1,["encrypt","decrypt"])}async function bX(X,$){let Q=await _$($),Z,H=Promise.resolve(),q=Promise.resolve(),G=!1,D=()=>{if(!G)G=!0,X.close()};return X.setReceive((O)=>{if(G)return;if(O.length<13||O[0]!==1){D();return}let M=M8(O.subarray(1,13)),T=M8(O.subarray(13));q=q.then(async()=>{if(G)return;try{let V=await crypto.subtle.decrypt({name:"AES-GCM",iv:M},Q,T);Z?.(new Uint8Array(V))}catch{D()}})}),{send(O){if(G)return;let M=M8(O);H=H.then(async()=>{if(G)return;try{let T=crypto.getRandomValues(new Uint8Array(12)),V=M8(T),j=await crypto.subtle.encrypt({name:"AES-GCM",iv:V},Q,M),k=new Uint8Array(j),v=new Uint8Array(13+k.byteLength);v[0]=1,v.set(T,1),v.set(k,13),X.send(v)}catch{D()}})},setReceive(O){Z=O},close(){D()}}}class A${buffer=[];waiters=[];ctrl=new AbortController;cleanup;ended=!1;failure=null;constructor(X){let $=(Q)=>{if(this.ended||this.failure)return;let Z=this.waiters.shift();if(Z){Z.resolve({value:Q,done:!1});return}this.buffer.push(Q)};try{let Q=X($,this.ctrl.signal);if(typeof Q==="function")this.cleanup=Q}catch(Q){this.failure=Q}}[Symbol.asyncIterator](){return{next:async()=>{if(this.buffer.length>0)return{value:this.buffer.shift(),done:!1};if(this.failure)throw this.failure;if(this.ended)return{value:void 0,done:!0};return new Promise((X,$)=>this.waiters.push({resolve:X,reject:$}))},return:async()=>{return this.dispose(),{value:void 0,done:!0}}}}cancel(){this.dispose()}[Symbol.dispose](){this.dispose()}dispose(){if(this.ended)return;this.ended=!0,this.ctrl.abort();try{this.cleanup?.()}catch{}while(this.waiters.length>0)this.waiters.shift().resolve({value:void 0,done:!0})}}var IX=null;function W8(){if(!IX)IX=host.runtime().then((X)=>X.surface());return IX}function c(X){return W8().then(X).catch(($)=>{if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] surface call failed",$);return})}function m(X){return W8().then(X)}class j0{element;onBoundsChange;observer=null;rafId=0;lastRect={x:0,y:0,width:0,height:0};dirty=!1;stopped=!1;constructor(X,$){this.element=X,this.onBoundsChange=$}start(){this.observer=new ResizeObserver(()=>this.markDirty()),this.observer.observe(this.element),this.scheduleFrame()}stop(){if(this.stopped=!0,this.observer?.disconnect(),this.observer=null,this.rafId)cancelAnimationFrame(this.rafId),this.rafId=0}markDirty(){this.dirty=!0}scheduleFrame(){if(this.stopped)return;this.rafId=requestAnimationFrame(()=>{this.flush(),this.scheduleFrame()})}flush(){let X=window.devicePixelRatio||1,$=this.element.getBoundingClientRect(),Q={x:Math.round($.x*X),y:Math.round($.y*X),width:Math.round($.width*X),height:Math.round($.height*X)};if(!this.dirty&&Q.x===this.lastRect.x&&Q.y===this.lastRect.y&&Q.width===this.lastRect.width&&Q.height===this.lastRect.height)return;this.dirty=!1,this.lastRect=Q,this.onBoundsChange(Q)}}class x0 extends HTMLElement{static observedAttributes=["src"];_surfaceId=null;_syncCtrl=null;_initPromise=null;_aborted=!1;_pendingSrc=null;_syncHidden=!1;_userHidden=!1;_layoutObserver=null;_unsubNavigate=null;_activeStreams=[];constructor(){super()}connectedCallback(){this._aborted=!1,this._syncHidden=!1,this._userHidden=!1;let X=new AbortController;this._unsubNavigate=()=>X.abort(),(async()=>{try{let $=await W8();if(X.signal.aborted)return;await this._waitForSurfaceId(X.signal);let Q=this._surfaceId;if(X.signal.aborted||Q==null)return;let Z=$.surfaceEvents({surfaceId:Q});this._activeStreams.push(Z);let H=$.downloadEvents({surfaceId:Q});this._activeStreams.push(H),(async()=>{try{for await(let q of H){if(X.signal.aborted)break;this.dispatchEvent(new CustomEvent("download-event",{detail:q}))}}catch{}})();for await(let q of Z){if(X.signal.aborted)break;this.dispatchEvent(new CustomEvent("surface-event",{detail:q}))}}catch($){if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] surfaceEvents stream failed",$)}})(),this._waitForLayout()}async _waitForSurfaceId(X){while(this._surfaceId==null&&!X.aborted){let $=this._initPromise;if($)try{await $}catch{return}else await new Promise((Q)=>setTimeout(Q,16))}}_waitForLayout(){if(this._layoutObserver)return;let X=()=>{if(!this.isConnected||this._aborted)return!0;let $=this.getBoundingClientRect();if($.width>0&&$.height>0){if(this.getAttribute("src")||this._pendingSrc||"")this.initSurface();return!0}return!1};requestAnimationFrame(()=>{if(X())return;this._layoutObserver=new ResizeObserver(()=>{if(X())this._layoutObserver?.disconnect(),this._layoutObserver=null}),this._layoutObserver.observe(this)})}disconnectedCallback(){this._aborted=!0,this._unsubNavigate?.(),this._unsubNavigate=null;for(let X of this._activeStreams)try{X.cancel?.()}catch{}if(this._activeStreams=[],this._layoutObserver?.disconnect(),this._layoutObserver=null,this._syncCtrl?.stop(),this._syncCtrl=null,this._surfaceId!=null){let X=this._surfaceId;this._surfaceId=null,c(($)=>$.remove({surfaceId:X}))}else if(this._initPromise)this._initPromise.then((X)=>{c(($)=>$.remove({surfaceId:X.surfaceId}))}).catch(()=>{});this._initPromise=null}attributeChangedCallback(X,$,Q){if(X!=="src")return;if(this._surfaceId!=null){let Z=this._surfaceId;c((H)=>H.navigate({surfaceId:Z,url:Q||""}))}else if(this._initPromise)this._pendingSrc=Q||"";else if(this.isConnected&&!this._aborted&&Q)this._waitForLayout()}setHidden(X){this._userHidden=X,this._applySurfaceHidden()}goBack(){let X=this._surfaceId;if(X!=null)c(($)=>$.goBack({surfaceId:X}))}reload(){let X=this._surfaceId;if(X!=null)c(($)=>$.reload({surfaceId:X}))}navigate(X){this.setAttribute("src",X)}async evaluate(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Z)=>Z.evaluate({surfaceId:Q,script:X,frameId:$?.frameId}))}async capabilities(){let X=this._surfaceId;if(X==null)return{evaluate:!1,crossOriginEval:!1,surfaceEvents:!1,nativeInputTrusted:!1,click:!1,type:!1,press:!1,scroll:!1,mouse:!1,dialogs:!1,console:!1,screenshot:!1,accessibilitySnapshot:!1,getBoundingRect:!1,frames:!1,downloads:!1,popups:!1,resolveAndClick:!1};return m(($)=>$.capabilities({surfaceId:X}))}async sendClick(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.click({surfaceId:$,...X}))}async sendType(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.type({surfaceId:$,text:X}))}async sendPress(X,$,Q){let Z=this._surfaceId;if(Z==null)return;await m((H)=>H.press({surfaceId:Z,key:X,modifiers:$,action:Q}))}async sendScroll(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.scroll({surfaceId:$,...X}))}async sendMouse(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.mouse({surfaceId:$,...X}))}async respondToDialog(X,$,Q){let Z=this._surfaceId;if(Z==null)return;await m((H)=>H.respondToDialog({surfaceId:Z,requestId:X,accept:$,text:Q}))}async setDialogTimeout(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.setDialogTimeout({surfaceId:$,ms:X}))}async waitForSelector(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.waitForSelector({surfaceId:Q,selector:X,timeoutMs:$}))}async waitForFunction(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.waitForFunction({surfaceId:Q,expression:X,...$}))}async getConsoleBuffer(X){let $=this._surfaceId;if($==null)return[];return await m((Q)=>Q.getConsoleBuffer({surfaceId:$,clear:X?.clear}))??[]}async getNavigationState(){let X=this._surfaceId;if(X==null)return{lastLoadEpoch:0,isLoading:!1,currentUrl:""};return m(($)=>$.getNavigationState({surfaceId:X}))}async accessibilitySnapshot(X){let $=this._surfaceId;if($==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Q)=>Q.accessibilitySnapshot({surfaceId:$,interestingOnly:X?.interestingOnly}))}async getBoundingRect(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.getBoundingRect({surfaceId:Q,selector:X,frameId:$?.frameId}))}async listFrames(){let X=this._surfaceId;if(X==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m(($)=>$.listFrames({surfaceId:X}))}async resolveAndClick(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.resolveAndClick({surfaceId:Q,selector:X,...$}))}async setDownloadPolicy(X,$){let Q=this._surfaceId;if(Q==null)return;await c((Z)=>Z.setDownloadPolicy({surfaceId:Q,policy:X,downloadDir:$}))}async waitForDownload(X){let $=this._surfaceId;if($==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Q)=>Q.waitForDownload({surfaceId:$,timeoutMs:X?.timeoutMs}))}async dismissPopup(X){await c(($)=>$.dismissPopup({newSurfaceId:X}))}async extendAdoptionTimeout(X,$){return m((Q)=>Q.extendPopupTimeout({newSurfaceId:X,gracePeriodMs:$}))}async screenshot(X){let $=this._surfaceId;if($==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Q)=>Q.screenshot({surfaceId:$,...X}))}_applySurfaceHidden(){let X=this._surfaceId;if(X==null)return;let $=this._userHidden||this._syncHidden;c((Q)=>Q.setHidden({surfaceId:X,hidden:$}))}_setupSyncCtrl(){this._syncCtrl=new j0(this,(X)=>{let $=this._surfaceId;if($==null)return;if(X.width===0&&X.height===0){if(!this._syncHidden)this._syncHidden=!0,this._applySurfaceHidden();return}if(this._syncHidden)this._syncHidden=!1,this._applySurfaceHidden();c((Z)=>Z.resize({surfaceId:$,x:X.x,y:X.y,w:X.width,h:X.height}))}),this._syncCtrl.start()}initSurface(){if(this._surfaceId!=null||this._initPromise!=null)return;let X=window.devicePixelRatio||1,$=this.getBoundingClientRect(),Q=this.getAttribute("adopt-popup-id"),Z=Q?Number(Q):NaN;if(Number.isFinite(Z)){let G=W8().then(async(D)=>{let O=await D.acceptPopup({newSurfaceId:Z,hostViewId:__buniteWebviewId,bounds:{x:Math.round($.x*X),y:Math.round($.y*X),width:Math.round($.width*X),height:Math.round($.height*X)}});if(!O.ok)throw Error(`acceptPopup failed: ${O.code}: ${O.message}`);return{surfaceId:Z}});this._initPromise=G,G.then((D)=>{if(this._initPromise!==G)return;if(this._aborted){c((O)=>O.remove({surfaceId:D.surfaceId}));return}this._surfaceId=D.surfaceId,this._setupSyncCtrl()}).catch((D)=>{if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] adopt-popup-id init failed",D);this._initPromise=null});return}let H=this._pendingSrc||this.getAttribute("src")||"";this._pendingSrc=null;let q=W8().then((G)=>G.init({src:H,x:Math.round($.x*X),y:Math.round($.y*X),width:Math.round($.width*X),height:Math.round($.height*X),hidden:this._userHidden}));this._initPromise=q,q.then((G)=>{if(this._initPromise!==q)return;if(this._aborted){c((D)=>D.remove({surfaceId:G.surfaceId}));return}if(this._surfaceId=G.surfaceId,this._userHidden)this._applySurfaceHidden();if(this._pendingSrc!=null){let D=this._pendingSrc;this._pendingSrc=null;let O=this._surfaceId;if(O!=null)c((M)=>M.navigate({surfaceId:O,url:D}))}this._setupSyncCtrl()}).catch(()=>{}).finally(()=>{if(this._initPromise===q)this._initPromise=null})}}if(typeof customElements<"u"){customElements.define("bunite-webview",x0);let X=()=>{c(($)=>$.bringAllVisiblesToFront())};document.addEventListener("pointerdown",X,!0),document.addEventListener("dragstart",()=>{c(($)=>$.setAllPassthrough({passthrough:!0}))},!0),document.addEventListener("dragend",()=>{c(($)=>$.setAllPassthrough({passthrough:!1})),X()},!0)}var kX=null,R8=null;function i8(){if(kX)return Promise.resolve(kX);if(R8)return R8;let X=(async()=>{let $=new WebSocket(`ws://localhost:${__buniteRpcSocketPort}/rpc?webviewId=${__buniteWebviewId}`);$.binaryType="arraybuffer",await new Promise((q,G)=>{$.addEventListener("open",()=>q(),{once:!0}),$.addEventListener("error",()=>G(Error("bunite preload ws connect failed")),{once:!0})});let Q=Uint8Array.from(atob(__buniteSecretKeyBase64),(q)=>q.charCodeAt(0)),Z=await bX(wX($),Q),H=jX({transport:xX(Z),mode:"native",origin:location.origin});return kX=H,H})();return R8=X,X.catch(()=>{if(R8===X)R8=null}),X}var r=window;r.__bunite??={};r.__buniteWebviewId=__buniteWebviewId;r.__buniteRpcSocketPort=__buniteRpcSocketPort;r.host??={};r.host.bootstrap=async(X)=>{return(await i8()).bootstrap(X)};r.host.runtime=async()=>(await i8()).runtime();r.host.releaseRef=async(X)=>{(await i8()).releaseRef(X)};r.host.getConnection=()=>i8();var k0=Symbol.for("bunite.console.buffer"),w0=200,z$=16,M$=50;r[k0]=[];var s8=r[k0];function W$(X){if(typeof X==="string")return X;if(X instanceof Error)return X.stack??X.message;try{return JSON.stringify(X)}catch{return String(X)}}var U8=null,b0=0,R$=1000;function B$(){if(U8)return U8;if(Date.now()<b0)return Promise.reject(Error("reporting cap cooldown"));return U8=(async()=>{return(await r.host.runtime()).reporting()})(),U8.catch(()=>{U8=null,b0=Date.now()+R$}),U8}var B8=[],V8=null;function I0(){if(V8)clearTimeout(V8),V8=null;if(B8.length===0)return;let X=B8;B8=[],B$().then(($)=>$.reportConsoleBatch({entries:X})).catch(()=>{})}function V$(){if(B8.length>=M$){I0();return}if(V8)return;V8=setTimeout(I0,z$)}function T$(){for(let X of["log","warn","error","info","debug"]){let $=console[X].bind(console);console[X]=(...Q)=>{try{$(...Q)}catch{}try{let Z={level:X,args:Q.map(W$),ts:Date.now()};if(s8.push(Z),s8.length>w0)s8.splice(0,s8.length-w0);B8.push(Z),V$()}catch{}}}}T$();
|
|
1
|
+
var pX=Symbol.for("bunite.rpc.CallDef"),uX=Symbol.for("bunite.rpc.StreamDef"),lX=Symbol.for("bunite.rpc.CapDef"),dX=Symbol.for("bunite.rpc.CapRefToken"),cX=Symbol.for("bunite.rpc.CapArrayToken"),nX=Symbol.for("bunite.rpc.CapRecordToken"),h0=Symbol.for("bunite.rpc.Schema");function e8(X){return{[dX]:!0,cap:X}}e8.array=(X)=>({[cX]:!0,cap:X});e8.record=(X)=>({[nX]:!0,cap:X});var n=e8;function j8(X){return typeof X==="object"&&X!==null&&X[dX]===!0}function x8(X){return typeof X==="object"&&X!==null&&X[cX]===!0}function w8(X){return typeof X==="object"&&X!==null&&X[nX]===!0}function b8(X){return typeof X==="object"&&X!==null&&X[pX]===!0}function I8(X){return typeof X==="object"&&X!==null&&X[uX]===!0}function _(X){return{[pX]:!0,idempotent:!!X?.idempotent,returns:X?.returns}}function J8(X){return{[uX]:!0,hint:X?.hint}}function a(X,$,Q){return{[lX]:!0,name:X,version:Q?.version!=null?String(Q.version):void 0,methods:$,disposal:Q?.disposal??void 0}}function k8(X){return typeof X==="object"&&X!==null&&X[lX]===!0}function XX(X){return typeof X==="object"&&X!==null&&X[h0]===!0}var QX;try{QX=new TextDecoder}catch(X){}var A,s,J=0;var J0=[],ZX=J0,HX=0,b={},C,N8,o=0,e=0,p,H8,l=[],E,oX={useRecords:!1,mapsAsObjects:!0};class v8{}var JX=new v8;JX.name="MessagePack 0xC1";var G8=!1,sX=2,iX,aX,rX;class X8{constructor(X){if(X){if(X.useRecords===!1&&X.mapsAsObjects===void 0)X.mapsAsObjects=!0;if(X.sequential&&X.trusted!==!1){if(X.trusted=!0,!X.structures&&X.useRecords!=!1){if(X.structures=[],!X.maxSharedStructures)X.maxSharedStructures=0}}if(X.structures)X.structures.sharedLength=X.structures.length;else if(X.getStructures)(X.structures=[]).uninitialized=!0,X.structures.sharedLength=0;if(X.int64AsNumber)X.int64AsType="number"}Object.assign(this,X)}unpack(X,$){if(A)return F0(()=>{return S8(),this?this.unpack(X,$):X8.prototype.unpack.call(oX,X,$)});if(!X.buffer&&X.constructor===ArrayBuffer)X=typeof Buffer<"u"?Buffer.from(X):new Uint8Array(X);if(typeof $==="object")s=$.end||X.length,J=$.start||0;else J=0,s=$>-1?$:X.length;HX=0,e=0,N8=null,ZX=J0,p=null,A=X;try{E=X.dataView||(X.dataView=new DataView(X.buffer,X.byteOffset,X.byteLength))}catch(Q){if(A=null,X instanceof Uint8Array)throw Q;throw Error("Source must be a Uint8Array or Buffer but was a "+(X&&typeof X=="object"?X.constructor.name:typeof X))}if(this instanceof X8){if(b=this,this.structures)return C=this.structures,y8($);else if(!C||C.length>0)C=[]}else if(b=oX,!C||C.length>0)C=[];return y8($)}unpackMultiple(X,$){let Q,Z=0;try{G8=!0;let H=X.length,q=this?this.unpack(X,H):m8.unpack(X,H);if($){if($(q,Z,J)===!1)return;while(J<H)if(Z=J,$(y8(),Z,J)===!1)return}else{Q=[q];while(J<H)Z=J,Q.push(y8());return Q}}catch(H){throw H.lastPosition=Z,H.values=Q,H}finally{G8=!1,S8()}}_mergeStructures(X,$){if(aX)X=aX.call(this,X);if(X=X||[],Object.isFrozen(X))X=X.map((Q)=>Q.slice(0));for(let Q=0,Z=X.length;Q<Z;Q++){let H=X[Q];if(H){if(H.isShared=!0,Q>=32)H.highByte=Q-32>>5}}X.sharedLength=X.length;for(let Q in $||[])if(Q>=0){let Z=X[Q],H=$[Q];if(H){if(Z)(X.restoreStructures||(X.restoreStructures=[]))[Q]=Z;X[Q]=H}}return this.structures=X}decode(X,$){return this.unpack(X,$)}}function y8(X){try{if(!b.trusted&&!G8){let Q=C.sharedLength||0;if(Q<C.length)C.length=Q}let $;if(b.randomAccessStructure&&A[J]<64&&A[J]>=32&&iX){if($=iX(A,J,s,b),A=null,!(X&&X.lazy)&&$)$=$.toJSON();J=s}else $=h();if(p)J=p.postBundlePosition,p=null;if(G8)C.restoreStructures=null;if(J==s){if(C&&C.restoreStructures)tX();if(C=null,A=null,H8)H8=null}else if(J>s)throw Error("Unexpected end of MessagePack data");else if(!G8){let Q;try{Q=JSON.stringify($,(Z,H)=>typeof H==="bigint"?`${H}n`:H).slice(0,100)}catch(Z){Q="(JSON view not available "+Z+")"}throw Error("Data read, but end of buffer not reached "+Q)}return $}catch($){if(C&&C.restoreStructures)tX();if(S8(),$ instanceof RangeError||$.message.startsWith("Unexpected end of buffer")||J>s)$.incomplete=!0;throw $}}function tX(){for(let X in C.restoreStructures)C[X]=C.restoreStructures[X];C.restoreStructures=null}function h(){let X=A[J++];if(X<160)if(X<128)if(X<64)return X;else{let $=C[X&63]||b.getStructures&&N0()[X&63];if($){if(!$.read)$.read=NX($,X&63);return $.read()}else return X}else if(X<144)if(X-=128,b.mapsAsObjects){let $={};for(let Q=0;Q<X;Q++){let Z=K0();if(Z==="__proto__")Z="__proto_";$[Z]=h()}return $}else{let $=new Map;for(let Q=0;Q<X;Q++)$.set(h(),h());return $}else{X-=144;let $=Array(X);for(let Q=0;Q<X;Q++)$[Q]=h();if(b.freezeData)return Object.freeze($);return $}else if(X<192){let $=X-160;if(e>=J)return N8.slice(J-o,(J+=$)-o);if(e==0&&s<140){let Q=$<16?GX($):G0($);if(Q!=null)return Q}return qX($)}else{let $;switch(X){case 192:return null;case 193:if(p)if($=h(),$>0)return p[1].slice(p.position1,p.position1+=$);else return p[0].slice(p.position0,p.position0-=$);return JX;case 194:return!1;case 195:return!0;case 196:if($=A[J++],$===void 0)throw Error("Unexpected end of buffer");return $X($);case 197:return $=E.getUint16(J),J+=2,$X($);case 198:return $=E.getUint32(J),J+=4,$X($);case 199:return K8(A[J++]);case 200:return $=E.getUint16(J),J+=2,K8($);case 201:return $=E.getUint32(J),J+=4,K8($);case 202:if($=E.getFloat32(J),b.useFloat32>2){let Q=h8[(A[J]&127)<<1|A[J+1]>>7];return J+=4,(Q*$+($>0?0.5:-0.5)>>0)/Q}return J+=4,$;case 203:return $=E.getFloat64(J),J+=8,$;case 204:return A[J++];case 205:return $=E.getUint16(J),J+=2,$;case 206:return $=E.getUint32(J),J+=4,$;case 207:if(b.int64AsType==="number")$=E.getUint32(J)*4294967296,$+=E.getUint32(J+4);else if(b.int64AsType==="string")$=E.getBigUint64(J).toString();else if(b.int64AsType==="auto"){if($=E.getBigUint64(J),$<=BigInt(2)<<BigInt(52))$=Number($)}else $=E.getBigUint64(J);return J+=8,$;case 208:return E.getInt8(J++);case 209:return $=E.getInt16(J),J+=2,$;case 210:return $=E.getInt32(J),J+=4,$;case 211:if(b.int64AsType==="number")$=E.getInt32(J)*4294967296,$+=E.getUint32(J+4);else if(b.int64AsType==="string")$=E.getBigInt64(J).toString();else if(b.int64AsType==="auto"){if($=E.getBigInt64(J),$>=BigInt(-2)<<BigInt(52)&&$<=BigInt(2)<<BigInt(52))$=Number($)}else $=E.getBigInt64(J);return J+=8,$;case 212:if($=A[J++],$==114)return H0(A[J++]&63);else{let Q=l[$];if(Q)if(Q.read)return J++,Q.read(h());else if(Q.noBuffer)return J++,Q();else return Q(A.subarray(J,++J));else throw Error("Unknown extension "+$)}case 213:if($=A[J],$==114)return J++,H0(A[J++]&63,A[J++]);else return K8(2);case 214:return K8(4);case 215:return K8(8);case 216:return K8(16);case 217:if($=A[J++],e>=J)return N8.slice(J-o,(J+=$)-o);return g0($);case 218:if($=E.getUint16(J),J+=2,e>=J)return N8.slice(J-o,(J+=$)-o);return f0($);case 219:if($=E.getUint32(J),J+=4,e>=J)return N8.slice(J-o,(J+=$)-o);return p0($);case 220:return $=E.getUint16(J),J+=2,X0($);case 221:return $=E.getUint32(J),J+=4,X0($);case 222:return $=E.getUint16(J),J+=2,$0($);case 223:return $=E.getUint32(J),J+=4,$0($);default:if(X>=224)return X-256;if(X===void 0){let Q=Error("Unexpected end of MessagePack data");throw Q.incomplete=!0,Q}throw Error("Unknown MessagePack token "+X)}}}var m0=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function NX(X,$){function Q(){if(Q.count++>sX){let H;try{H=X.read=Function("r","return function(){return "+(b.freezeData?"Object.freeze":"")+"({"+X.map((q)=>q==="__proto__"?"__proto_:r()":m0.test(q)?q+":r()":"["+JSON.stringify(q)+"]:r()").join(",")+"})}")(h)}catch(q){return sX=1/0,Q()}if(X.highByte===0)X.read=eX($,X.read);return H()}let Z={};for(let H=0,q=X.length;H<q;H++){let G=X[H];if(G==="__proto__")G="__proto_";Z[G]=h()}if(b.freezeData)return Object.freeze(Z);return Z}if(Q.count=0,X.highByte===0)return eX($,Q);return Q}var eX=(X,$)=>{return function(){let Q=A[J++];if(Q===0)return $();let Z=X<32?-(X+(Q<<5)):X+(Q<<5),H=C[Z]||N0()[Z];if(!H)throw Error("Record id is not defined for "+Z);if(!H.read)H.read=NX(H,X);return H.read()}};function N0(){let X=F0(()=>{return A=null,b.getStructures()});return C=b._mergeStructures(X,C)}var qX=A8,g0=A8,f0=A8,p0=A8;function A8(X){let $;if(X<16){if($=GX(X))return $}if(X>64&&QX)return QX.decode(A.subarray(J,J+=X));let Q=J+X,Z=[];$="";while(J<Q){let H=A[J++];if((H&128)===0)Z.push(H);else if((H&224)===192){let q=A[J++]&63,G=(H&31)<<6|q;if(G<128)Z.push(65533);else Z.push(G)}else if((H&240)===224){let q=A[J++]&63,G=A[J++]&63,F=(H&31)<<12|q<<6|G;if(F<2048||F>=55296&&F<=57343)Z.push(65533);else Z.push(F)}else if((H&248)===240){let q=A[J++]&63,G=A[J++]&63,F=A[J++]&63,O=(H&7)<<18|q<<12|G<<6|F;if(O<65536||O>1114111)Z.push(65533);else if(O>65535)O-=65536,Z.push(O>>>10&1023|55296),O=56320|O&1023,Z.push(O);else Z.push(O)}else Z.push(65533);if(Z.length>=4096)$+=f.apply(String,Z),Z.length=0}if(Z.length>0)$+=f.apply(String,Z);return $}function X0(X){let $=Array(X);for(let Q=0;Q<X;Q++)$[Q]=h();if(b.freezeData)return Object.freeze($);return $}function $0(X){if(b.mapsAsObjects){let $={};for(let Q=0;Q<X;Q++){let Z=K0();if(Z==="__proto__")Z="__proto_";$[Z]=h()}return $}else{let $=new Map;for(let Q=0;Q<X;Q++)$.set(h(),h());return $}}var f=String.fromCharCode;function G0(X){let $=J,Q=Array(X);for(let Z=0;Z<X;Z++){let H=A[J++];if((H&128)>0){J=$;return}Q[Z]=H}return f.apply(String,Q)}function GX(X){if(X<4)if(X<2)if(X===0)return"";else{let $=A[J++];if(($&128)>1){J-=1;return}return f($)}else{let $=A[J++],Q=A[J++];if(($&128)>0||(Q&128)>0){J-=2;return}if(X<3)return f($,Q);let Z=A[J++];if((Z&128)>0){J-=3;return}return f($,Q,Z)}else{let $=A[J++],Q=A[J++],Z=A[J++],H=A[J++];if(($&128)>0||(Q&128)>0||(Z&128)>0||(H&128)>0){J-=4;return}if(X<6)if(X===4)return f($,Q,Z,H);else{let q=A[J++];if((q&128)>0){J-=5;return}return f($,Q,Z,H,q)}else if(X<8){let q=A[J++],G=A[J++];if((q&128)>0||(G&128)>0){J-=6;return}if(X<7)return f($,Q,Z,H,q,G);let F=A[J++];if((F&128)>0){J-=7;return}return f($,Q,Z,H,q,G,F)}else{let q=A[J++],G=A[J++],F=A[J++],O=A[J++];if((q&128)>0||(G&128)>0||(F&128)>0||(O&128)>0){J-=8;return}if(X<10)if(X===8)return f($,Q,Z,H,q,G,F,O);else{let M=A[J++];if((M&128)>0){J-=9;return}return f($,Q,Z,H,q,G,F,O,M)}else if(X<12){let M=A[J++],T=A[J++];if((M&128)>0||(T&128)>0){J-=10;return}if(X<11)return f($,Q,Z,H,q,G,F,O,M,T);let V=A[J++];if((V&128)>0){J-=11;return}return f($,Q,Z,H,q,G,F,O,M,T,V)}else{let M=A[J++],T=A[J++],V=A[J++],j=A[J++];if((M&128)>0||(T&128)>0||(V&128)>0||(j&128)>0){J-=12;return}if(X<14)if(X===12)return f($,Q,Z,H,q,G,F,O,M,T,V,j);else{let k=A[J++];if((k&128)>0){J-=13;return}return f($,Q,Z,H,q,G,F,O,M,T,V,j,k)}else{let k=A[J++],v=A[J++];if((k&128)>0||(v&128)>0){J-=14;return}if(X<15)return f($,Q,Z,H,q,G,F,O,M,T,V,j,k,v);let u=A[J++];if((u&128)>0){J-=15;return}return f($,Q,Z,H,q,G,F,O,M,T,V,j,k,v,u)}}}}}function Q0(){let X=A[J++],$;if(X<192)$=X-160;else switch(X){case 217:$=A[J++];break;case 218:$=E.getUint16(J),J+=2;break;case 219:$=E.getUint32(J),J+=4;break;default:throw Error("Expected string")}return A8($)}function $X(X){return b.copyBuffers?Uint8Array.prototype.slice.call(A,J,J+=X):A.subarray(J,J+=X)}function K8(X){let $=A[J++];if(l[$]){let Q;return l[$](A.subarray(J,Q=J+=X),(Z)=>{J=Z;try{return h()}finally{J=Q}})}else throw Error("Unknown extension type "+$)}var Z0=Array(4096);function K0(){let X=A[J++];if(X>=160&&X<192){if(X=X-160,e>=J)return N8.slice(J-o,(J+=X)-o);else if(!(e==0&&s<180))return qX(X)}else return J--,Y0(h());let $=(X<<5^(X>1?E.getUint16(J):X>0?A[J]:0))&4095,Q=Z0[$],Z=J,H=J+X-3,q,G=0;if(Q&&Q.bytes==X){while(Z<H){if(q=E.getUint32(Z),q!=Q[G++]){Z=1879048192;break}Z+=4}H+=3;while(Z<H)if(q=A[Z++],q!=Q[G++]){Z=1879048192;break}if(Z===H)return J=Z,Q.string;H-=3,Z=J}Q=[],Z0[$]=Q,Q.bytes=X;while(Z<H)q=E.getUint32(Z),Q.push(q),Z+=4;H+=3;while(Z<H)q=A[Z++],Q.push(q);let F=X<16?GX(X):G0(X);if(F!=null)return Q.string=F;return Q.string=qX(X)}function Y0(X){if(typeof X==="string")return X;if(typeof X==="number"||typeof X==="boolean"||typeof X==="bigint")return X.toString();if(X==null)return X+"";if(b.allowArraysInMapKeys&&Array.isArray(X)&&X.flat().every(($)=>["string","number","boolean","bigint"].includes(typeof $)))return X.flat().toString();throw Error(`Invalid property type for record: ${typeof X}`)}var H0=(X,$)=>{let Q=h().map(Y0),Z=X;if($!==void 0)X=X<32?-(($<<5)+X):($<<5)+X,Q.highByte=$;let H=C[X];if(H&&(H.isShared||G8))(C.restoreStructures||(C.restoreStructures=[]))[X]=H;return C[X]=Q,Q.read=NX(Q,Z),Q.read()};l[0]=()=>{};l[0].noBuffer=!0;l[66]=(X)=>{let $=X.byteLength%8||8,Q=BigInt(X[0]&128?X[0]-256:X[0]);for(let Z=1;Z<$;Z++)Q<<=BigInt(8),Q+=BigInt(X[Z]);if(X.byteLength!==$){let Z=new DataView(X.buffer,X.byteOffset,X.byteLength),H=(q,G)=>{let F=G-q;if(F<=40){let V=Z.getBigUint64(q);for(let j=q+8;j<G;j+=8)V<<=BigInt(64),V|=Z.getBigUint64(j);return V}let O=q+(F>>4<<3),M=H(q,O),T=H(O,G);return M<<BigInt((G-O)*8)|T};Q=Q<<BigInt((Z.byteLength-$)*8)|H($,Z.byteLength)}return Q};var q0={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==="function"?AggregateError:null};l[101]=()=>{let X=h();if(!q0[X[0]]){let $=Error(X[1],{cause:X[2]});return $.name=X[0],$}return q0[X[0]](X[1],{cause:X[2]})};l[105]=(X)=>{if(b.structuredClone===!1)throw Error("Structured clone extension is disabled");let $=E.getUint32(J-4);if(!H8)H8=new Map;let Q=A[J],Z;if(Q>=144&&Q<160||Q==220||Q==221)Z=[];else if(Q>=128&&Q<144||Q==222||Q==223)Z=new Map;else if((Q>=199&&Q<=201||Q>=212&&Q<=216)&&A[J+1]===115)Z=new Set;else Z={};let H={target:Z};H8.set($,H);let q=h();if(!H.used)return H.target=q;else Object.assign(Z,q);if(Z instanceof Map)for(let[G,F]of q.entries())Z.set(G,F);if(Z instanceof Set)for(let G of Array.from(q))Z.add(G);return Z};l[112]=(X)=>{if(b.structuredClone===!1)throw Error("Structured clone extension is disabled");let $=E.getUint32(J-4),Q=H8.get($);return Q.used=!0,Q.target};l[115]=()=>new Set(h());var KX=["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64","BigInt64","BigUint64"].map((X)=>X+"Array"),u0=typeof globalThis==="object"?globalThis:window;l[116]=(X)=>{let $=X[0],Q=Uint8Array.prototype.slice.call(X,1).buffer,Z=KX[$];if(!Z){if($===16)return Q;if($===17)return new DataView(Q);throw Error("Could not find typed array for code "+$)}return new u0[Z](Q)};l[120]=()=>{let X=h();return new RegExp(X[0],X[1])};var l0=[];l[98]=(X)=>{let $=(X[0]<<24)+(X[1]<<16)+(X[2]<<8)+X[3],Q=J;return J+=$-X.length,p=l0,p=[Q0(),Q0()],p.position0=0,p.position1=0,p.postBundlePosition=J,J=Q,h()};l[255]=(X)=>{if(X.length==4)return new Date((X[0]*16777216+(X[1]<<16)+(X[2]<<8)+X[3])*1000);else if(X.length==8)return new Date(((X[0]<<22)+(X[1]<<14)+(X[2]<<6)+(X[3]>>2))/1e6+((X[3]&3)*4294967296+X[4]*16777216+(X[5]<<16)+(X[6]<<8)+X[7])*1000);else if(X.length==12)return new Date(((X[0]<<24)+(X[1]<<16)+(X[2]<<8)+X[3])/1e6+((X[4]&128?-281474976710656:0)+X[6]*1099511627776+X[7]*4294967296+X[8]*16777216+(X[9]<<16)+(X[10]<<8)+X[11])*1000);else return new Date("invalid")};function F0(X){if(rX)rX();let $=s,Q=J,Z=HX,H=o,q=e,G=N8,F=ZX,O=H8,M=p,T=new Uint8Array(A.slice(0,s)),V=C,j=C.slice(0,C.length),k=b,v=G8,u=X();return s=$,J=Q,HX=Z,o=H,e=q,N8=G,ZX=F,H8=O,p=M,A=T,G8=v,C=V,C.splice(0,C.length,...j),b=k,E=new DataView(A.buffer,A.byteOffset,A.byteLength),u}function S8(){A=null,H8=null,C=null}function L0(X){if(X.unpack)l[X.type]=X.unpack;else l[X.type]=X}var h8=Array(147);for(let X=0;X<256;X++)h8[X]=+("1e"+Math.floor(45.15-X*0.30103));var m8=new X8({useRecords:!1}),d0=m8.unpack,c0=m8.unpackMultiple,n0=m8.unpack;var o0=new Float32Array(1),x$=new Uint8Array(o0.buffer,0,4);var f8;try{f8=new TextEncoder}catch(X){}var p8,u8,F8=typeof Buffer<"u",g8=F8?function(X){return Buffer.allocUnsafeSlow(X)}:Uint8Array,_0=F8?Buffer:Uint8Array,D0=F8?4294967296:2144337920,K,_8,I,N=0,d,S=null,s0,i0=21760,a0=/[\u0080-\uFFFF]/,Y8=Symbol("record-id");class L8 extends X8{constructor(X){super(X);this.offset=0;let $,Q,Z,H,q,G=_0.prototype.utf8Write?function(Y,z){return K.utf8Write(Y,z,K.byteLength-z)}:f8&&f8.encodeInto?function(Y,z){return f8.encodeInto(Y,K.subarray(z)).written}:!1,F=this;if(!X)X={};let O=X&&X.sequential,M=X.structures||X.saveStructures,T=X.maxSharedStructures;if(T==null)T=M?32:0;if(T>8160)throw Error("Maximum maxSharedStructure is 8160");if(X.structuredClone&&X.moreTypes==null)this.moreTypes=!0;let V=X.maxOwnStructures;if(V==null)V=M?32:64;if(!this.structures&&X.useRecords!=!1)this.structures=[];let j=T>32||V+T>64,k=T+64,v=T+V+64;if(v>8256)throw Error("Maximum maxSharedStructure + maxOwnStructure is 8192");let u=[],g=0,Q8=0;this.pack=this.encode=function(Y,z){if(!K)K=new g8(8192),I=K.dataView||(K.dataView=new DataView(K.buffer,0,8192)),N=0;if(d=K.length-10,d-N<2048)K=new g8(K.length),I=K.dataView||(K.dataView=new DataView(K.buffer,0,K.length)),d=K.length-10,N=0;else N=N+7&2147483640;if(Q=N,z&R0)N+=z&255;if(q=F.structuredClone?new Map:null,F.bundleStrings&&typeof Y!=="string")S=[],S.size=1/0;else S=null;if(H=F.structures,H){if(H.uninitialized)H=F._mergeStructures(F.getStructures());let L=H.sharedLength||0;if(L>T)throw Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to "+H.sharedLength);if(!H.transitions){H.transitions=Object.create(null);for(let D=0;D<L;D++){let R=H[D];if(!R)continue;let B,W=H.transitions;for(let x=0,w=R.length;x<w;x++){let t=R[x];if(B=W[t],!B)B=W[t]=Object.create(null);W=B}W[Y8]=D+64}this.lastNamedStructuresLength=L}if(!O)H.nextId=L+64}if(Z)Z=!1;let U;try{if(F.randomAccessStructure&&Y&&typeof Y==="object")if(Y.constructor===Object)fX(Y);else if(Y.constructor!==Map&&!Array.isArray(Y)&&!u8.some((D)=>Y instanceof D))fX(Y.toJSON?Y.toJSON():Y);else y(Y);else y(Y);let L=S;if(S)O0(Q,y,0);if(q&&q.idsToInsert){let D=q.idsToInsert.sort((x,w)=>x.offset>w.offset?1:-1),R=D.length,B=-1;while(L&&R>0){let x=D[--R].offset+Q;if(x<L.stringsPosition+Q&&B===-1)B=0;if(x>L.position+Q){if(B>=0)B+=6}else{if(B>=0)I.setUint32(L.position+Q,I.getUint32(L.position+Q)+B),B=-1;L=L.previous,R++}}if(B>=0&&L)I.setUint32(L.position+Q,I.getUint32(L.position+Q)+B);if(N+=D.length*6,N>d)Z8(N);F.offset=N;let W=r0(K.subarray(Q,N),D);return q=null,W}if(F.offset=N,z&M0)return K.start=Q,K.end=N,K;return K.subarray(Q,N)}catch(L){throw U=L,L}finally{if(H){if(E8(),Z&&F.saveStructures){let L=H.sharedLength||0,D=K.subarray(Q,N),R=t0(H,F);if(!U){if(F.saveStructures(R,R.isCompatible)===!1)return F.pack(Y,z);if(F.lastNamedStructuresLength=L,K.length>1073741824)K=null;return D}}}if(K.length>1073741824)K=null;if(z&W0)N=Q}};let E8=()=>{if(Q8<10)Q8++;let Y=H.sharedLength||0;if(H.length>Y&&!O)H.length=Y;if(g>1e4){if(H.transitions=null,Q8=0,g=0,u.length>0)u=[]}else if(u.length>0&&!O){for(let z=0,U=u.length;z<U;z++)u[z][Y8]=0;u=[]}},r8=(Y)=>{var z=Y.length;if(z<16)K[N++]=144|z;else if(z<65536)K[N++]=220,K[N++]=z>>8,K[N++]=z&255;else K[N++]=221,I.setUint32(N,z),N+=4;for(let U=0;U<z;U++)y(Y[U])},y=(Y)=>{if(N>d)K=Z8(N);var z=typeof Y,U;if(z==="string"){let L=Y.length;if(S&&L>=4&&L<4096){if((S.size+=L)>i0){let W,x=(S[0]?S[0].length*3+S[1].length:0)+10;if(N+x>d)K=Z8(N+x);let w;if(S.position)w=S,K[N]=200,N+=3,K[N++]=98,W=N-Q,N+=4,O0(Q,y,0),I.setUint16(W+Q-3,N-Q-W);else K[N++]=214,K[N++]=98,W=N-Q,N+=4;S=["",""],S.previous=w,S.size=0,S.position=W}let B=a0.test(Y);S[B?0:1]+=Y,K[N++]=193,y(B?-L:L);return}let D;if(L<32)D=1;else if(L<256)D=2;else if(L<65536)D=3;else D=5;let R=L*3;if(N+R>d)K=Z8(N+R);if(L<64||!G){let B,W,x,w=N+D;for(B=0;B<L;B++)if(W=Y.charCodeAt(B),W<128)K[w++]=W;else if(W<2048)K[w++]=W>>6|192,K[w++]=W&63|128;else if((W&64512)===55296&&((x=Y.charCodeAt(B+1))&64512)===56320)W=65536+((W&1023)<<10)+(x&1023),B++,K[w++]=W>>18|240,K[w++]=W>>12&63|128,K[w++]=W>>6&63|128,K[w++]=W&63|128;else K[w++]=W>>12|224,K[w++]=W>>6&63|128,K[w++]=W&63|128;U=w-N-D}else U=G(Y,N+D);if(U<32)K[N++]=160|U;else if(U<256){if(D<2)K.copyWithin(N+2,N+1,N+1+U);K[N++]=217,K[N++]=U}else if(U<65536){if(D<3)K.copyWithin(N+3,N+2,N+2+U);K[N++]=218,K[N++]=U>>8,K[N++]=U&255}else{if(D<5)K.copyWithin(N+5,N+3,N+3+U);K[N++]=219,I.setUint32(N,U),N+=4}N+=U}else if(z==="number")if(Y>>>0===Y)if(Y<32||Y<128&&this.useRecords===!1||Y<64&&!this.randomAccessStructure)K[N++]=Y;else if(Y<256)K[N++]=204,K[N++]=Y;else if(Y<65536)K[N++]=205,K[N++]=Y>>8,K[N++]=Y&255;else K[N++]=206,I.setUint32(N,Y),N+=4;else if(Y>>0===Y)if(Y>=-32)K[N++]=256+Y;else if(Y>=-128)K[N++]=208,K[N++]=Y+256;else if(Y>=-32768)K[N++]=209,I.setInt16(N,Y),N+=2;else K[N++]=210,I.setInt32(N,Y),N+=4;else{let L;if((L=this.useFloat32)>0&&Y<4294967296&&Y>=-2147483648){K[N++]=202,I.setFloat32(N,Y);let D;if(L<4||(D=Y*h8[(K[N]&127)<<1|K[N+1]>>7])>>0===D){N+=4;return}else N--}K[N++]=203,I.setFloat64(N,Y),N+=8}else if(z==="object"||z==="function")if(!Y)K[N++]=192;else{if(q){let D=q.get(Y);if(D){if(!D.id){let R=q.idsToInsert||(q.idsToInsert=[]);D.id=R.push(D)}K[N++]=214,K[N++]=112,I.setUint32(N,D.id),N+=4;return}else q.set(Y,{offset:N-Q})}let L=Y.constructor;if(L===Object)C8(Y);else if(L===Array)r8(Y);else if(L===Map)if(this.mapAsEmptyObject)K[N++]=128;else{if(U=Y.size,U<16)K[N++]=128|U;else if(U<65536)K[N++]=222,K[N++]=U>>8,K[N++]=U&255;else K[N++]=223,I.setUint32(N,U),N+=4;for(let[D,R]of Y)y(D),y(R)}else{for(let D=0,R=p8.length;D<R;D++){let B=u8[D];if(Y instanceof B){let W=p8[D];if(W.write){if(W.type)K[N++]=212,K[N++]=W.type,K[N++]=0;let O8=W.write.call(this,Y);if(O8===Y)if(Array.isArray(Y))r8(Y);else C8(Y);else y(O8);return}let x=K,w=I,t=N;K=null;let q8;try{q8=W.pack.call(this,Y,(O8)=>{if(K=x,x=null,N+=O8,N>d)Z8(N);return{target:K,targetView:I,position:N-O8}},y)}finally{if(x)K=x,I=w,N=t,d=K.length-10}if(q8){if(q8.length+N>d)Z8(q8.length+N);N=U0(q8,K,N,W.type)}return}}if(Array.isArray(Y))r8(Y);else{if(Y.toJSON){let D=Y.toJSON();if(D!==Y)return y(D)}if(z==="function")return y(this.writeFunction&&this.writeFunction(Y));C8(Y)}}}else if(z==="boolean")K[N++]=Y?195:194;else if(z==="bigint"){if(Y<9223372036854776000&&Y>=-9223372036854776000)K[N++]=211,I.setBigInt64(N,Y);else if(Y<18446744073709552000&&Y>0)K[N++]=207,I.setBigUint64(N,Y);else if(this.largeBigIntToFloat)K[N++]=203,I.setFloat64(N,Number(Y));else if(this.largeBigIntToString)return y(Y.toString());else if(this.useBigIntExtension||this.moreTypes){let L=Y<0?BigInt(-1):BigInt(0),D;if(Y>>BigInt(65536)===L){let R=BigInt(18446744073709552000)-BigInt(1),B=[];while(!0){if(B.push(Y&R),Y>>BigInt(63)===L)break;Y>>=BigInt(64)}D=new Uint8Array(new BigUint64Array(B).buffer),D.reverse()}else{let R=Y<0,B=(R?~Y:Y).toString(16);if(B.length%2)B="0"+B;else if(parseInt(B.charAt(0),16)>=8)B="00"+B;if(F8)D=Buffer.from(B,"hex");else{D=new Uint8Array(B.length/2);for(let W=0;W<D.length;W++)D[W]=parseInt(B.slice(W*2,W*2+2),16)}if(R)for(let W=0;W<D.length;W++)D[W]=~D[W]}if(D.length+N>d)Z8(D.length+N);N=U0(D,K,N,66);return}else throw RangeError(Y+" was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string");N+=8}else if(z==="undefined")if(this.encodeUndefinedAsNil)K[N++]=192;else K[N++]=212,K[N++]=0,K[N++]=0;else throw Error("Unknown type: "+z)},vX=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?(Y)=>{let z;if(this.skipValues){z=[];for(let D in Y)if((typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(D))&&!this.skipValues.includes(Y[D]))z.push(D)}else z=Object.keys(Y);let U=z.length;if(U<16)K[N++]=128|U;else if(U<65536)K[N++]=222,K[N++]=U>>8,K[N++]=U&255;else K[N++]=223,I.setUint32(N,U),N+=4;let L;if(this.coercibleKeyAsNumber)for(let D=0;D<U;D++){L=z[D];let R=Number(L);y(isNaN(R)?L:R),y(Y[L])}else for(let D=0;D<U;D++)y(L=z[D]),y(Y[L])}:(Y)=>{K[N++]=222;let z=N-Q;N+=2;let U=0;for(let L in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(L))y(L),y(Y[L]),U++;if(U>65535)throw Error('Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object');K[z+++Q]=U>>8,K[z+Q]=U&255},hX=this.useRecords===!1?vX:X.progressiveRecords&&!j?(Y)=>{let z,U=H.transitions||(H.transitions=Object.create(null)),L=N++-Q,D;for(let R in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(R)){if(z=U[R],z)U=z;else{let B=Object.keys(Y),W=U;U=H.transitions;let x=0;for(let w=0,t=B.length;w<t;w++){let q8=B[w];if(z=U[q8],!z)z=U[q8]=Object.create(null),x++;U=z}if(L+Q+1==N)N--,t8(U,B,x);else gX(U,B,L,x);D=!0,U=W[R]}y(Y[R])}if(!D){let R=U[Y8];if(R)K[L+Q]=R;else gX(U,Object.keys(Y),L,0)}}:(Y)=>{let z,U=H.transitions||(H.transitions=Object.create(null)),L=0;for(let R in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(R)){if(z=U[R],!z)z=U[R]=Object.create(null),L++;U=z}let D=U[Y8];if(D)if(D>=96&&j)K[N++]=((D-=96)&31)+96,K[N++]=D>>5;else K[N++]=D;else t8(U,U.__keys__||Object.keys(Y),L);for(let R in Y)if(typeof Y.hasOwnProperty!=="function"||Y.hasOwnProperty(R))y(Y[R])},mX=typeof this.useRecords=="function"&&this.useRecords,C8=mX?(Y)=>{mX(Y)?hX(Y):vX(Y)}:hX,Z8=(Y)=>{let z;if(Y>16777216){if(Y-Q>D0)throw Error("Packed buffer would be larger than maximum buffer size");z=Math.min(D0,Math.round(Math.max((Y-Q)*(Y>67108864?1.25:2),4194304)/4096)*4096)}else z=(Math.max(Y-Q<<2,K.length-1)>>12)+1<<12;let U=new g8(z);if(I=U.dataView||(U.dataView=new DataView(U.buffer,0,z)),Y=Math.min(Y,K.length),K.copy)K.copy(U,0,Q,Y);else U.set(K.slice(Q,Y));return N-=Q,Q=0,d=U.length-10,K=U},t8=(Y,z,U)=>{let L=H.nextId;if(!L)L=64;if(L<k&&this.shouldShareStructure&&!this.shouldShareStructure(z)){if(L=H.nextOwnId,!(L<v))L=k;H.nextOwnId=L+1}else{if(L>=v)L=k;H.nextId=L+1}let D=z.highByte=L>=96&&j?L-96>>5:-1;if(Y[Y8]=L,Y.__keys__=z,H[L-64]=z,L<k)if(z.isShared=!0,H.sharedLength=L-63,Z=!0,D>=0)K[N++]=(L&31)+96,K[N++]=D;else K[N++]=L;else{if(D>=0)K[N++]=213,K[N++]=114,K[N++]=(L&31)+96,K[N++]=D;else K[N++]=212,K[N++]=114,K[N++]=L;if(U)g+=Q8*U;if(u.length>=V)u.shift()[Y8]=0;u.push(Y),y(z)}},gX=(Y,z,U,L)=>{let D=K,R=N,B=d,W=Q;if(K=_8,N=0,Q=0,!K)_8=K=new g8(8192);d=K.length-10,t8(Y,z,L),_8=K;let x=N;if(K=D,N=R,d=B,Q=W,x>1){let w=N+x-1;if(w>d)Z8(w);let t=U+Q;K.copyWithin(t+x,t+1,N),K.set(_8.slice(0,x),t),N=w}else K[U+Q]=_8[0]},fX=(Y)=>{let z=s0(Y,K,Q,N,H,Z8,(U,L,D)=>{if(D)return Z=!0;N=L;let R=K;if(y(U),E8(),R!==K)return{position:N,targetView:I,target:K};return N},this);if(z===0)return C8(Y);N=z}}useBuffer(X){K=X,K.dataView||(K.dataView=new DataView(K.buffer,K.byteOffset,K.byteLength)),I=K.dataView,N=0}set position(X){N=X}get position(){return N}clearSharedData(){if(this.structures)this.structures=[];if(this.typedStructs)this.typedStructs=[]}}u8=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,v8];p8=[{pack(X,$,Q){let Z=X.getTime()/1000;if((this.useTimestamp32||X.getMilliseconds()===0)&&Z>=0&&Z<4294967296){let{target:H,targetView:q,position:G}=$(6);H[G++]=214,H[G++]=255,q.setUint32(G,Z)}else if(Z>0&&Z<4294967296){let{target:H,targetView:q,position:G}=$(10);H[G++]=215,H[G++]=255,q.setUint32(G,X.getMilliseconds()*4000000+(Z/1000/4294967296>>0)),q.setUint32(G+4,Z)}else if(isNaN(Z)){if(this.onInvalidDate)return $(0),Q(this.onInvalidDate());let{target:H,targetView:q,position:G}=$(3);H[G++]=212,H[G++]=255,H[G++]=255}else{let{target:H,targetView:q,position:G}=$(15);H[G++]=199,H[G++]=12,H[G++]=255,q.setUint32(G,X.getMilliseconds()*1e6),q.setBigInt64(G+4,BigInt(Math.floor(Z)))}}},{pack(X,$,Q){if(this.setAsEmptyObject)return $(0),Q({});let Z=Array.from(X),{target:H,position:q}=$(this.moreTypes?3:0);if(this.moreTypes)H[q++]=212,H[q++]=115,H[q++]=0;Q(Z)}},{pack(X,$,Q){let{target:Z,position:H}=$(this.moreTypes?3:0);if(this.moreTypes)Z[H++]=212,Z[H++]=101,Z[H++]=0;Q([X.name,X.message,X.cause])}},{pack(X,$,Q){let{target:Z,position:H}=$(this.moreTypes?3:0);if(this.moreTypes)Z[H++]=212,Z[H++]=120,Z[H++]=0;Q([X.source,X.flags])}},{pack(X,$){if(this.moreTypes)YX(X,16,$);else FX(F8?Buffer.from(X):new Uint8Array(X),$)}},{pack(X,$){let Q=X.constructor;if(Q!==_0&&this.moreTypes)YX(X,KX.indexOf(Q.name),$);else FX(X,$)}},{pack(X,$){if(this.moreTypes)YX(X,17,$);else FX(F8?Buffer.from(X):new Uint8Array(X),$)}},{pack(X,$){let{target:Q,position:Z}=$(1);Q[Z]=193}}];function YX(X,$,Q,Z){let H=X.byteLength;if(H+1<256){var{target:q,position:G}=Q(4+H);q[G++]=199,q[G++]=H+1}else if(H+1<65536){var{target:q,position:G}=Q(5+H);q[G++]=200,q[G++]=H+1>>8,q[G++]=H+1&255}else{var{target:q,position:G,targetView:F}=Q(7+H);q[G++]=201,F.setUint32(G,H+1),G+=4}if(q[G++]=116,q[G++]=$,!X.buffer)X=new Uint8Array(X);q.set(new Uint8Array(X.buffer,X.byteOffset,X.byteLength),G)}function FX(X,$){let Q=X.byteLength;var Z,H;if(Q<256){var{target:Z,position:H}=$(Q+2);Z[H++]=196,Z[H++]=Q}else if(Q<65536){var{target:Z,position:H}=$(Q+3);Z[H++]=197,Z[H++]=Q>>8,Z[H++]=Q&255}else{var{target:Z,position:H,targetView:q}=$(Q+5);Z[H++]=198,q.setUint32(H,Q),H+=4}Z.set(X,H)}function U0(X,$,Q,Z){let H=X.length;switch(H){case 1:$[Q++]=212;break;case 2:$[Q++]=213;break;case 4:$[Q++]=214;break;case 8:$[Q++]=215;break;case 16:$[Q++]=216;break;default:if(H<256)$[Q++]=199,$[Q++]=H;else if(H<65536)$[Q++]=200,$[Q++]=H>>8,$[Q++]=H&255;else $[Q++]=201,$[Q++]=H>>24,$[Q++]=H>>16&255,$[Q++]=H>>8&255,$[Q++]=H&255}return $[Q++]=Z,$.set(X,Q),Q+=H,Q}function r0(X,$){let Q,Z=$.length*6,H=X.length-Z;while(Q=$.pop()){let{offset:q,id:G}=Q;X.copyWithin(q+Z,q,H),Z-=6;let F=q+Z;X[F++]=214,X[F++]=105,X[F++]=G>>24,X[F++]=G>>16&255,X[F++]=G>>8&255,X[F++]=G&255,H=q}return X}function O0(X,$,Q){if(S.length>0){I.setUint32(S.position+X,N+Q-S.position-X),S.stringsPosition=N-X;let Z=S;S=null,$(Z[0]),$(Z[1])}}function LX(X){if(X.Class){if(!X.pack&&!X.write)throw Error("Extension has no pack or write function");if(X.pack&&!X.type)throw Error("Extension has no type (numeric code to identify the extension)");u8.unshift(X.Class),p8.unshift(X)}L0(X)}function t0(X,$){return X.isCompatible=(Q)=>{let Z=!Q||($.lastNamedStructuresLength||0)===Q.length;if(!Z)$._mergeStructures(Q);return Z},X}var z0=new L8({useRecords:!1}),e0=z0.pack,X$=z0.pack;var M0=512,W0=1024,R0=2048;var V0=80;class r{capId;constructor(X){this.capId=X}}var $$=new Set(["hello","goaway","call","result","cancel","stream","drop","cap_revoked"]);function DX(X){if(typeof X!=="object"||X===null)return!1;let $=X,Q=$.op;if(typeof Q!=="string"||!$$.has(Q))return!1;switch(Q){case"hello":return $.v===1&&($.mode==="native"||$.mode==="web")&&Array.isArray($.features)&&typeof $.maxBytes==="number"&&typeof $.origin==="string";case"goaway":return $.reason===void 0||typeof $.reason==="string";case"call":return typeof $.id==="number"&&typeof $.method==="string"&&typeof $.target==="object"&&$.target!==null&&$.target.kind==="cap"&&typeof $.target.id==="number";case"result":return typeof $.id==="number"&&($.ok===!0||$.ok===!1);case"cancel":return typeof $.id==="number";case"stream":return typeof $.id==="number"&&typeof $.ev==="string"&&($.ev==="next"||$.ev==="credit"||$.ev==="end"||$.ev==="error");case"drop":return Array.isArray($.caps);case"cap_revoked":if(!Array.isArray($.capIds))return!1;for(let Z of $.capIds)if(typeof Z!=="number"||!Number.isInteger(Z)||Z<0||Z>4294967295)return!1;return!0}}var B0=!1;function Q$(){if(B0)return;B0=!0,LX({Class:r,type:V0,pack:(X)=>Z$(X.capId),unpack:(X)=>new r(q$(X))})}function UX(){return Q$(),{packr:new L8({useRecords:!0,sequential:!0,moreTypes:!0}),unpackr:new X8({useRecords:!0,sequential:!0,moreTypes:!0})}}function Z$(X){let $=new Uint8Array(5),Q=X>>>0,Z=0;while(Q>=128)$[Z++]=Q&127|128,Q>>>=7;return $[Z++]=Q&127,$.subarray(0,Z)}var H$=5;function q$(X){let $=0,Q=0,Z=Math.min(X.length,H$);for(let H=0;H<Z;H++){let q=X[H];if($|=(q&127)<<Q,(q&128)===0)return $>>>0;Q+=7}throw Error("Truncated or oversize varuint")}var OX=67108864,AX=1,l8="bunite.",d8="bootstrap";class P extends Error{code;details;retry;constructor(X){super(X.message??X.code);this.name="IpcError",this.code=X.code,this.details=X.details,this.retry=X.retry}toStatus(){return{code:this.code,message:this.message,details:this.details,retry:this.retry}}}var z8=a("bunite.BrowserWindow",{focus:_(),close:_(),setBounds:_(),setTitle:_(),id:_({idempotent:!0}),label:_({idempotent:!0}),minimize:_(),unminimize:_(),maximize:_(),unmaximize:_(),toggleMaximize:_(),getState:_({idempotent:!0}),stateWatch:J8(),beginMoveDrag:_()}),_X=a("bunite.Window",{create:_({returns:n(z8)}),list:_({returns:n.array(z8),idempotent:!0}),current:_({returns:n(z8),idempotent:!0}),focus:_(),close:_()}),c8=a("bunite.FileRef",{text:_({idempotent:!0}),bytes:_({idempotent:!0}),path:_({idempotent:!0}),revoke:_()},{disposal:{method:"revoke"}}),zX=a("bunite.Dialogs",{openFile:_({returns:n.array(c8)}),saveFile:_({returns:n(c8)}),showMessage:_()}),MX=a("bunite.Clipboard",{readText:_({idempotent:!0}),writeText:_(),readBytes:_({idempotent:!0}),writeBytes:_()}),WX=a("bunite.Shell",{openExternal:_(),showItemInFolder:_()}),RX=a("bunite.PageReporting",{reportConsoleBatch:_()}),BX=a("bunite.Surface",{init:_(),resize:_(),remove:_(),setHidden:_(),setMasks:_(),setAllPassthrough:_(),bringAllVisiblesToFront:_(),navigate:_(),goBack:_(),reload:_(),evaluate:_(),capabilities:_(),click:_(),type:_(),press:_(),scroll:_(),mouse:_(),screenshot:_(),waitForSelector:_(),waitForFunction:_(),respondToDialog:_(),setDialogTimeout:_(),getConsoleBuffer:_({idempotent:!0}),surfaceEvents:J8(),dialogs:J8(),consoleEvents:J8(),getNavigationState:_({idempotent:!0}),accessibilitySnapshot:_(),getBoundingRect:_({idempotent:!0}),listFrames:_({idempotent:!0}),downloadEvents:J8(),waitForDownload:_(),setDownloadPolicy:_(),acceptPopup:_(),dismissPopup:_(),extendPopupTimeout:_(),resolveAndClick:_()}),M8=a("bunite.Runtime",{window:_({returns:n(_X),idempotent:!0}),dialogs:_({returns:n(zX),idempotent:!0}),clipboard:_({returns:n(MX),idempotent:!0}),shell:_({returns:n(WX),idempotent:!0}),appName:_({idempotent:!0}),appVersion:_({idempotent:!0}),theme:_({idempotent:!0}),themeWatch:J8(),surface:_({returns:n(BX),idempotent:!0}),reporting:_({returns:n(RX),idempotent:!0}),popupMetrics:_({idempotent:!0})}),$8={Runtime:1,Window:2,Dialogs:3,FileRef:4,Clipboard:5,Shell:6,BrowserWindow:7,Surface:8,PageReporting:9},J$=new Map([[M8,$8.Runtime],[_X,$8.Window],[zX,$8.Dialogs],[c8,$8.FileRef],[MX,$8.Clipboard],[WX,$8.Shell],[z8,$8.BrowserWindow],[BX,$8.Surface],[RX,$8.PageReporting]]);function VX(X){return J$.get(X)}var o8=0,EX=1,P0=0,E0=1,D8=2,CX=128,s8=1024,C0=1024,N$=s8*4,G$=500,K$=32,Y$=8,F$=1024;function L$(X){let $=X?.initialBudget;if(typeof $!=="number"||!Number.isFinite($)||!Number.isInteger($)||$<1)return K$;return Math.min($,F$)}var n8=null;class jX{entries=new Map;nextCapId=D8;capLimit;constructor(X=s8){this.capLimit=X}install(X,$){if(this.entries.has(X))throw Error(`cap-id ${X} already installed`);let Q={capId:X,...$};return this.entries.set(X,Q),Q}allocate(X){if(this.entries.size>=this.capLimit)throw new P({code:"resource_exhausted",message:`cap-table limit ${this.capLimit}`,details:{reason:"max_caps_per_connection"}});let $=this.nextCapId++;while(this.entries.has($))$=this.nextCapId++;return this.install($,X)}get(X){return this.entries.get(X)}release(X,$=1){let Q=this.entries.get(X);if(!Q)return!1;if(Q.refCount=Math.max(0,Q.refCount-$),Q.refCount===0&&X>=D8)return this.entries.delete(X),!0;return!1}delete(X){if(X<D8)return!1;return this.entries.delete(X)}clear(){this.entries.clear(),this.nextCapId=D8}size(){return this.entries.size}values(){return this.entries.values()}}var D$={origin:"",topOrigin:"",partition:"default",isAppRes:!1,isMainFrame:!1,userGesture:!1,level:"untrusted"},j0=Symbol("bunite.rpc.ExportedCap"),T0=Symbol("bunite.rpc.CapProxyMeta");function U$(X){return typeof X==="object"&&X!==null&&X[j0]===!0}var O$=typeof FinalizationRegistry<"u"?new FinalizationRegistry((X)=>{if(X.dropped())return;let $=X.connRef.deref();if(!$||$.closed)return;$._dropFromFinalizer(X.capId)}):{register:()=>{}};class x0{transport;capTable;pending=new Map;clientStreams=new Map;serverStreams=new Map;serverCallChildren=new Map;serverActiveCalls=new Map;registry=new Map;rootInstances=new Map;revokedCapIds=new Set;closeHandlers=new Set;observers={};nextCallId=1;remoteHello=null;remoteReady;resolveRemoteReady;rejectRemoteReady;closed_=!1;maxBytes;maxInFlightCalls;mode;origin;features;attestation;peerId;policy;constructor(X){this.transport=X.transport,this.mode=X.mode,this.origin=X.origin,this.features=X.features??[],this.maxBytes=X.maxBytes??OX,this.maxInFlightCalls=X.maxInFlightCalls??C0,this.attestation=X.attestation??D$,this.peerId=X.peerId??"peer",this.policy=X.policy,this.capTable=new jX(X.capLimit??s8),this.capTable.install(o8,{typeId:P0,cap:null,impl:null,refCount:1}),this.capTable.install(EX,{typeId:E0,cap:M8,impl:X.runtime??null,refCount:1}),this.remoteReady=new Promise(($,Q)=>{this.resolveRemoteReady=$,this.rejectRemoteReady=Q}),this.remoteReady.catch(()=>{}),this.transport.setReceive(($)=>this.handleFrame($)),this.transport.send({op:"hello",v:AX,mode:this.mode,features:this.features,maxBytes:this.maxBytes,origin:this.origin})}get closed(){return this.closed_}onClose(X){return this.closeHandlers.add(X),()=>this.closeHandlers.delete(X)}on(X,$){let Q=this.observers[X];if(!Q)Q=new Set,this.observers[X]=Q;return Q.add($),()=>{Q.delete($)}}emitObs(X,$){let Q=this.observers[X];if(!Q||Q.size===0)return;for(let Z of Q)try{Z($)}catch{}}markRevoked(X){this.revokedCapIds.add(X);while(this.revokedCapIds.size>N$){let $=this.revokedCapIds.values().next().value;if($===void 0)break;this.revokedCapIds.delete($)}}serve(X,$,Q){this.assertNotFrameworkName(X.name);let Z=Q?.ifExists??"throw";if(this.registry.get(X.name))switch(Z){case"throw":throw new P({code:"already_exists",message:`cap "${X.name}" already served`,details:{reason:"name_collision"}});case"skip":return this.makeHandle([]);case"replace":return this.replace(X,$),this.makeHandle([X.name])}return this.registry.set(X.name,{cap:X,impl:$,version:X.version}),this.makeHandle([X.name])}makeHandle(X){let $={names:X,[Symbol.dispose]:()=>this.unserve($)};return $}serveAll(X,$,Q){let Z=Q?.ifExists??"throw";for(let q of Object.keys(X.roots)){let G=X.roots[q];this.assertNotFrameworkName(G.name);let F=this.registry.get(G.name);if(F){if(Z==="throw")throw new P({code:"already_exists",message:`cap "${G.name}" already served`,details:{reason:"name_collision"}});if(Z==="replace"&&F.version!==G.version)throw new P({code:"failed_precondition",message:`version mismatch on replace for "${G.name}" (current "${F.version}", new "${G.version}")`,details:{reason:"version_mismatch"}})}}let H=[];for(let q of Object.keys(X.roots)){let G=X.roots[q],F=$[q];if(this.serve(G,F,{ifExists:Z}).names.length>0)H.push(G.name)}return this.makeHandle(H)}unserve(X){let $=k8(X)?[X.name]:Array.from(X.names),Q=[];for(let Z of $){if(!this.registry.delete(Z))continue;let H=this.rootInstances.get(Z);if(H!==void 0){let q=this.capTable.get(H);if(q)this.invokeServerDisposal(q);this.rootInstances.delete(Z),this.capTable.delete(H),Q.push(H)}}if(Q.length>0)this.transport.send({op:"cap_revoked",capIds:Q}),this.emitObs("revoke",{capIds:Q,reason:"unserve"})}replace(X,$){let Q=this.registry.get(X.name);if(!Q)throw new P({code:"not_found",message:`cap "${X.name}" not served`});if(Q.version!==X.version)throw new P({code:"failed_precondition",message:`version mismatch (current "${Q.version}", new "${X.version}")`,details:{reason:"version_mismatch"}});Q.impl=$,Q.cap=X;let Z=this.rootInstances.get(X.name);if(Z!==void 0){let H=this.capTable.get(Z);if(H)H.impl=$,H.cap=X}this.emitObs("revoke",{capIds:Z!==void 0?[Z]:[],reason:"replace"})}assertNotFrameworkName(X){if(X.startsWith(l8))throw new P({code:"already_exists",message:`cap name "${X}" uses reserved prefix "${l8}"`,details:{reason:"reserved_namespace"}})}runtimeProxy=null;runtime(){if(!this.runtimeProxy)this.runtimeProxy=this.makeCapProxy(M8,EX);return this.runtimeProxy}async bootstrap(X){if(k8(X))return this._bootstrapCap(X);if(XX(X))return this._bootstrapSchema(X);throw new P({code:"invalid_argument",message:"bootstrap target must be CapDef or Schema"})}async _bootstrapCap(X){await this.remoteReady;let $={name:X.name};if(X.version!=null)$.version=X.version;let Q=await this.sendCallTyped(o8,d8,$,void 0);if(!(Q instanceof r))throw new P({code:"invalid_argument",message:"bootstrap did not return a CapRef"});return this.makeCapProxy(X,Q.capId)}async _bootstrapSchema(X){let $=Object.keys(X.roots),Q=await Promise.allSettled($.map((q)=>this._bootstrapCap(X.roots[q]))),Z=Q.find((q)=>q.status==="rejected");if(Z){for(let q of Q)if(q.status==="fulfilled")try{this.releaseRef(q.value)}catch{}throw Z.reason}let H={};for(let q=0;q<$.length;q++)H[$[q]]=Q[q].value;return H}handleFrame(X){if(this.closed_)return;switch(X.op){case"hello":this.handleHello(X);return;case"call":this.handleCall(X);return;case"result":this.handleResult(X);return;case"cancel":this.handleCancel(X);return;case"stream":this.handleStreamFrame(X);return;case"drop":this.handleDrop(X);return;case"cap_revoked":this.handleCapRevoked(X);return;case"goaway":this.handleGoaway(X);return;default:this.handleUnknownFrame(X);return}}handleUnknownFrame(X){let $=X?.id;if(typeof $==="number"){this.transport.send({op:"result",id:$,ok:!1,error:{code:"invalid_argument",message:"unknown opcode"}});return}this.transport.send({op:"goaway",reason:"invalid_argument",error:{code:"invalid_argument",message:"unknown opcode"}}),this.shutdown("invalid_argument")}handleHello(X){this.remoteHello=X,this.resolveRemoteReady(X)}handleGoaway(X){this.rejectRemoteReady(new P(X.error??{code:"unavailable",message:X.reason??"peer goaway"})),this.shutdown(X.reason??"remote goaway")}handleCapRevoked(X){for(let $ of X.capIds){this.markRevoked($);let Q=new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}});for(let[Z,H]of this.pending)if(H.capId===$){if(this.pending.delete(Z),H.timer)clearTimeout(H.timer);H.reject(Q)}for(let[Z,H]of this.clientStreams)if(H.capId===$)this.clientStreams.delete(Z),H.fail(Q)}}async handleCall(X){if(X.target.id===o8&&X.method===d8){await this.handleBootstrap(X);return}let $=this.capTable.get(X.target.id);if(!$)return this.emitObs("call",{capId:X.target.id,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found",`cap-id ${X.target.id} not found`);let Q=$.cap;if(!Q||!$.impl)return this.emitObs("call",{capId:X.target.id,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found","cap has no impl");let Z=Q.methods[X.method];if(!Z)return this.emitObs("call",{capId:X.target.id,capName:Q.name,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found",`method "${X.method}" on cap "${Q.name}"`);let H=$.impl[X.method];if(typeof H!=="function")return this.emitObs("call",{capId:X.target.id,capName:Q.name,method:X.method,callId:X.id,result:"not_found"}),this.sendError(X.id,"not_found",`method "${X.method}" has no handler`);if(this.serverActiveCalls.size+this.serverStreams.size>=this.maxInFlightCalls)return this.emitObs("call",{capId:X.target.id,capName:Q.name,method:X.method,callId:X.id,result:"resource_exhausted"}),this.sendError(X.id,"resource_exhausted",`in-flight calls limit ${this.maxInFlightCalls}`,{reason:"max_concurrent_calls"});await this.invokeServerMethod(X,Q,Z,H)}async handleBootstrap(X){let $=X.args??{},Q=$.name;if(typeof Q!=="string")return this.emitObs("bootstrap",{name:String(Q),attestation:this.attestation,result:"invalid_argument"}),this.sendError(X.id,"invalid_argument","bootstrap requires {name: string}");let Z=$.version!=null?String($.version):void 0,H=this.registry.get(Q);if(!H)return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"not_found"}),this.sendError(X.id,"not_found",`cap "${Q}" not served`);let q=H.version;if(q!=null&&Z!=null&&q!==Z)return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"version_mismatch"}),this.sendError(X.id,"failed_precondition",`version mismatch (server "${q}", client "${Z}")`,{reason:"version_mismatch"});if(this.policy){let F;try{F=await this.policy(Q,this.attestation)}catch(O){return this.emitObs("error",{phase:"policy",error:O instanceof Error?O:Error(String(O))}),this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"internal"}),this.sendError(X.id,"internal","policy threw")}if(typeof F!=="boolean")return this.emitObs("error",{phase:"policy",error:Error(`policy must return boolean (got ${typeof F})`)}),this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"internal"}),this.sendError(X.id,"internal","policy returned non-boolean");if(!F)return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"denied"}),this.sendError(X.id,"failed_precondition","policy denied",{reason:"unauthorized"})}let G=this.rootInstances.get(Q);if(G!==void 0){let F=this.capTable.get(G);if(F)F.refCount+=1;else this.rootInstances.delete(Q),G=void 0}if(G===void 0)try{G=this.capTable.allocate({typeId:VX(H.cap)??CX,cap:H.cap,impl:H.impl,refCount:1}).capId,this.rootInstances.set(Q,G)}catch(F){if(F instanceof P){let O=F.code==="resource_exhausted"?"resource_exhausted":"internal";return this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:O}),this.sendError(X.id,F.code,F.message,F.details)}throw F}this.emitObs("bootstrap",{name:Q,version:Z,attestation:this.attestation,result:"ok",capId:G}),this.transport.send({op:"result",id:X.id,ok:!0,value:new r(G)})}async invokeServerMethod(X,$,Q,Z){let H=this.makeCallCtx(X);if(I8(Q)){let q=L$(Q.hint);try{let G=()=>Z(X.args,H),F=n8,M=(F?()=>F.run({callId:X.id},G):G)();this.runServerStream(X.id,M,H,q,$,X.method,X.target.id)}catch(G){this.emitObs("stream",{capId:X.target.id,capName:$.name,method:X.method,callId:X.id,event:"error"}),this.transport.send({op:"stream",id:X.id,ev:"error",error:TX(G)})}return}if(b8(Q)){let q=performance.now(),G=Q.idempotent?void 0:this.armServerDeadline(X,H);this.serverActiveCalls.set(X.id,{ctrl:H._ctrl,capId:X.target.id,capName:$.name,method:X.method,startedAt:q});let F=A$(Q.returns),O=()=>Promise.resolve(Z(X.args,H)),M=n8,T=M?()=>M.run({callId:X.id},O):O;try{let V=await T();if(G)clearTimeout(G);if(!this.serverActiveCalls.delete(X.id))return;let j=F(V);this.transport.send({op:"result",id:X.id,ok:!0,value:j}),this.emitObs("call",{capId:X.target.id,capName:$.name,method:X.method,callId:X.id,durationMs:performance.now()-q,result:"ok"})}catch(V){if(G)clearTimeout(G);if(!this.serverActiveCalls.delete(X.id))return;let j=TX(V);this.sendErrorFromStatus(X.id,j),this.emitObs("call",{capId:X.target.id,capName:$.name,method:X.method,callId:X.id,durationMs:performance.now()-q,result:j.code})}return}this.sendError(X.id,"not_found","unknown method kind")}armServerDeadline(X,$){let Q=X.meta?.deadlineMs;if(!Q)return;return setTimeout(()=>{$._ctrl.abort()},Q)}makeCallCtx(X){let $=new AbortController;return{callId:X.id,peerId:this.peerId,attestation:this.attestation,signal:$.signal,deadline:X.meta?.deadlineMs,_ctrl:$,exportCap:(Z,H)=>this.exportCap(Z,H)}}exportCap(X,$){let Q=VX(X)??CX,Z=this.capTable.allocate({typeId:Q,cap:X,impl:$,refCount:1});return{[j0]:!0,cap:X,capId:Z.capId,typeId:Z.typeId}}runServerStream(X,$,Q,Z,H,q,G){let F=$[Symbol.asyncIterator](),O=Q._ctrl,M={iter:F,abort:O,cancelled:!1,credit:Z,creditWaker:null,capId:G,capName:H.name,method:q,callId:X,count:0};this.serverStreams.set(X,M),this.emitObs("stream",{capId:G,capName:H.name,method:q,callId:X,event:"start"});let T=()=>{if(M.credit>0||M.cancelled)return Promise.resolve();return new Promise((j)=>{M.creditWaker=j})};(async()=>{let j=!1;try{while(!M.cancelled){if(M.credit===0)await T();if(M.cancelled)break;let{done:k,value:v}=await F.next();if(k)break;if(M.cancelled)break;M.credit-=1,M.count+=1,this.transport.send({op:"stream",id:X,ev:"next",value:v})}}catch(k){j=!0,this.transport.send({op:"stream",id:X,ev:"error",error:TX(k)}),this.emitObs("stream",{capId:G,capName:H.name,method:q,callId:X,event:"error",count:M.count})}finally{if(!j)this.transport.send({op:"stream",id:X,ev:"end"}),this.emitObs("stream",{capId:G,capName:H.name,method:q,callId:X,event:M.cancelled?"cancel":"end",count:M.count});this.serverStreams.delete(X)}})()}handleResult(X){let $=this.pending.get(X.id);if($){if(this.pending.delete(X.id),this.serverCallChildren.delete(X.id),$.timer)clearTimeout($.timer);if(X.ok){let Z=$.decodeReturn?$.decodeReturn(X.value):X.value;$.resolve(Z)}else $.reject(new P(X.error));return}let Q=this.clientStreams.get(X.id);if(Q){this.clientStreams.delete(X.id);let Z=X.ok?new P({code:"invalid_argument",message:"stream method returned result frame"}):new P(X.error);Q.fail(Z)}}handleCancel(X){let $=this.serverStreams.get(X.id);if($)$.cancelled=!0,$.abort.abort(),$.iter?.return?.(),this.serverStreams.delete(X.id);let Q=this.serverActiveCalls.get(X.id);if(Q)this.serverActiveCalls.delete(X.id),Q.ctrl.abort(),this.transport.send({op:"result",id:X.id,ok:!1,error:{code:"cancelled",message:X.reason}}),this.emitObs("call",{capId:Q.capId,capName:Q.capName,method:Q.method,callId:X.id,durationMs:performance.now()-Q.startedAt,result:"cancelled"});for(let[Z,H]of this.serverCallChildren){if(H.parentId!==X.id)continue;if(this.serverCallChildren.delete(Z),this.pending.has(Z))this.transport.send({op:"cancel",id:Z,reason:X.reason})}}releaseRef(X){if(typeof X!=="object"||X===null)return;let $=X[T0];if(!$||$.dropped)return;$.dropped=!0,this.sendDrop($.capId)}sendDrop(X){if(this.closed_)return;if(X<D8)return;this.transport.send({op:"drop",caps:[{id:X,delta:1}]})}handleStreamFrame(X){if(X.ev==="credit"){let Q=this.serverStreams.get(X.id);if(!Q)return;Q.credit+=X.credit?.messages??0;let Z=Q.creditWaker;Q.creditWaker=null,Z?.();return}let $=this.clientStreams.get(X.id);if(!$)return;switch(X.ev){case"next":$.push(X.value);return;case"end":$.end(),this.clientStreams.delete(X.id);return;case"error":$.fail(new P(X.error)),this.clientStreams.delete(X.id);return}}handleDrop(X){for(let{id:$,delta:Q}of X.caps)if(this.capTable.release($,Q)){for(let[H,q]of this.rootInstances)if(q===$){this.rootInstances.delete(H);break}}}sendError(X,$,Q,Z){let H={code:$,message:Q};if(Z!==void 0)H.details=Z;this.transport.send({op:"result",id:X,ok:!1,error:H})}sendErrorFromStatus(X,$){this.transport.send({op:"result",id:X,ok:!1,error:$})}nextId(){return this.nextCallId++}sendCallTyped(X,$,Q,Z,H,q){if(this.closed_)return Promise.reject(new P({code:"unavailable",message:"connection closed"}));if(this.revokedCapIds.has(X))return Promise.reject(new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}}));if(this.pending.size>=this.maxInFlightCalls)return Promise.reject(new P({code:"resource_exhausted",message:`in-flight calls limit ${this.maxInFlightCalls}`,details:{reason:"max_concurrent_calls"}}));let G=this.nextId();return new Promise((F,O)=>{let M=new AbortController,T={resolve:F,reject:O,abort:M,decodeReturn:Z,startedAt:performance.now(),capId:X,method:$,capName:q,kind:"call"};if(H?.deadlineMs)T.timer=setTimeout(()=>{if(this.pending.delete(G))this.transport.send({op:"cancel",id:G,reason:"deadline_exceeded"}),O(new P({code:"deadline_exceeded"}))},H.deadlineMs+G$);this.pending.set(G,T);let V=H;if(V?.parentCallId===void 0&&n8){let j=n8.getStore();if(j)V={...V??{},parentCallId:j.callId}}if(V?.parentCallId!==void 0)this.serverCallChildren.set(G,{parentId:V.parentCallId});this.transport.send({op:"call",id:G,target:{kind:"cap",id:X},method:$,args:Q,meta:V})})}openClientStream(X,$,Q,Z,H){if(this.closed_){let M=PX(X,0,()=>{},()=>{});return M.fail(new P({code:"unavailable",message:"connection closed"})),M.stream}if(this.revokedCapIds.has(X)){let M=PX(X,0,()=>{},()=>{});return M.fail(new P({code:"failed_precondition",message:"cap revoked",details:{reason:"revoked"}})),M.stream}let q=this.nextId(),O=PX(X,q,()=>{if(this.clientStreams.delete(q))this.transport.send({op:"cancel",id:q,reason:"client_cancel"})},(M)=>{if(this.closed_||!this.clientStreams.has(q))return;this.transport.send({op:"stream",id:q,ev:"credit",credit:{messages:M}})});return this.clientStreams.set(q,O),this.transport.send({op:"call",id:q,target:{kind:"cap",id:X},method:$,args:Q,meta:Z}),O.stream}makeCapProxy(X,$){let Q={},Z={capId:$,dropped:!1};Q[T0]=Z;let H=()=>{if(Z.dropped)return;Z.dropped=!0,this.sendDrop($)};for(let G of Object.keys(X.methods)){let F=X.methods[G];if(I8(F))Q[G]=(O)=>this.openClientStream($,G,O,void 0,X.name);else if(b8(F)){let O=_$(F.returns,(M,T)=>this.makeCapProxy(M,T));Q[G]=(M)=>this.sendCallTyped($,G,M,O,void 0,X.name)}}let q=X.disposal;if(q){let G=this;Q[Symbol.dispose]=()=>{try{let F=Q[q.method]?.();if(F&&typeof F.then==="function")F.catch((O)=>G.emitObs("error",{phase:"dispose",error:O instanceof Error?O:Error(String(O))}))}catch(F){G.emitObs("error",{phase:"dispose",error:F instanceof Error?F:Error(String(F))})}H()}}if(typeof FinalizationRegistry<"u")O$.register(Q,{connRef:new WeakRef(this),capId:$,dropped:()=>Z.dropped});return Q}_dropFromFinalizer(X){try{this.sendDrop(X)}catch{}}shutdown(X="shutdown"){if(this.closed_)return;this.closed_=!0;for(let $ of this.pending.values()){if($.timer)clearTimeout($.timer);$.reject(new P({code:"unavailable",message:X}))}this.pending.clear();for(let $ of this.clientStreams.values())$.fail(new P({code:"unavailable",message:X}));this.clientStreams.clear();for(let $ of this.serverStreams.values())$.cancelled=!0,$.abort.abort(),$.iter?.return?.();this.serverStreams.clear();for(let $ of this.serverActiveCalls.values())$.ctrl.abort();this.serverActiveCalls.clear();for(let $ of this.capTable.values())this.invokeServerDisposal($);if(this.capTable.clear(),!this.remoteHello)this.rejectRemoteReady(new P({code:"unavailable",message:X}));for(let $ of this.closeHandlers)try{$()}catch{}this.closeHandlers.clear();try{this.transport.close()}catch{}}invokeServerDisposal(X){let $=X.cap;if(!$)return;let Q=$.disposal;if(!Q)return;let Z=X.impl,H=Z?.[Q.method];if(!H)return;try{H.call(Z,void 0,void 0)}catch{}}}function A$(X){if(!X)return(Q)=>Q;let $=(Q,Z)=>{if(!U$(Q))throw new P({code:"failed_precondition",message:"expected ctx.exportCap return for cap method",details:{reason:"unregistered_cap_return"}});if(Q.cap!==Z)throw new P({code:"failed_precondition",message:"exported cap type mismatch with method returns",details:{reason:"unregistered_cap_return"}});return new r(Q.capId)};if(j8(X))return(Q)=>$(Q,X.cap);if(x8(X))return(Q)=>{if(!Array.isArray(Q))throw new P({code:"invalid_argument",message:"expected ExportedCap[] for cap.array method"});return Q.map((Z)=>$(Z,X.cap))};if(w8(X))return(Q)=>{if(!Q||typeof Q!=="object")throw new P({code:"invalid_argument",message:"expected Record<string, ExportedCap> for cap.record method"});let Z={};for(let H of Object.keys(Q))Z[H]=$(Q[H],X.cap);return Z};return(Q)=>Q}function _$(X,$){if(!X)return;if(j8(X)){let Q=X.cap;return(Z)=>{if(!(Z instanceof r))throw new P({code:"invalid_argument",message:"expected CapRef"});return $(Q,Z.capId)}}if(x8(X)){let Q=X.cap,Z=Q.disposal;return(H)=>{if(!Array.isArray(H))throw new P({code:"invalid_argument",message:"expected array"});let q=H.map((G)=>{if(!(G instanceof r))throw new P({code:"invalid_argument",message:"expected CapRef in array"});return $(Q,G.capId)});return z$(q,Z),q}}if(w8(X)){let Q=X.cap;return(Z)=>{if(!Z||typeof Z!=="object")throw new P({code:"invalid_argument",message:"expected record"});let H={};for(let q of Object.keys(Z)){let G=Z[q];if(!(G instanceof r))throw new P({code:"invalid_argument",message:"expected CapRef in record"});H[q]=$(Q,G.capId)}return H}}return}function z$(X,$){if(!$)return;X[Symbol.dispose]=()=>{for(let Q of X)Q[Symbol.dispose]?.call(Q)}}function TX(X){if(X instanceof P)return X.toStatus();if(X instanceof Error)return{code:"internal",message:X.message};return{code:"internal",message:String(X)}}function PX(X,$,Q,Z){let H=[],q=[],G=!1,F=null,O=!1,M=0;function T(){if(M+=1,M>=Y$)Z(M),M=0}function V(){if(H.length>0){let g=H.shift();return T(),{value:g,done:!1}}if(F)return null;if(G||O)return{value:void 0,done:!0};return null}function j(){let g=V();if(g)return Promise.resolve(g);if(F)return Promise.reject(F);return new Promise((Q8,E8)=>q.push({resolve:Q8,reject:E8}))}function k(){while(q.length>0){let g=q.shift(),Q8=V();if(Q8){g.resolve(Q8);continue}if(F){g.reject(F);continue}q.unshift(g);break}}function v(){if(O||G||F)return;O=!0,Q(),k()}let u={[Symbol.asyncIterator]:()=>({next:j,return:()=>{return v(),Promise.resolve({value:void 0,done:!0})},throw:(g)=>{return v(),Promise.reject(g)}}),[Symbol.dispose]:v,cancel:v};return{capId:X,stream:u,push(g){if(O||G||F)return;H.push(g),k()},end(){G=!0,k()},fail(g){F=g,k()}}}function xX(X){return new x0(X)}function wX(X,$={}){let Q=UX(),Z;return X.setReceive((H)=>{let q;try{q=Q.unpackr.unpack(H)}catch(G){$.onProtocolError?.(`unpack failed: ${G instanceof Error?G.message:String(G)}`),X.close();return}if(!DX(q)){$.onProtocolError?.("malformed frame"),X.close();return}Z?.(q)}),{send(H){let q=Q.packr.pack(H);X.send(q instanceof Uint8Array?q:new Uint8Array(q))},setReceive(H){Z=H},close(){X.close()}}}function bX(X){if("binaryType"in X)try{X.binaryType="arraybuffer"}catch{}let $,Q=(Z)=>{if(!$)return;let H=Z.data;if(H instanceof Uint8Array){$(H);return}if(H instanceof ArrayBuffer){$(new Uint8Array(H));return}if(typeof Blob<"u"&&H instanceof Blob){H.arrayBuffer().then((q)=>$?.(new Uint8Array(q)));return}};return X.addEventListener("message",Q),{send(Z){X.send(Z)},setReceive(Z){$=Z},close(){X.removeEventListener?.("message",Q),X.close?.()}}}function W8(X){let $=new ArrayBuffer(X.byteLength);return new Uint8Array($).set(X),$}async function M$(X){return crypto.subtle.importKey("raw",W8(X),"AES-GCM",!1,["encrypt","decrypt"])}async function IX(X,$){let Q=await M$($),Z,H=Promise.resolve(),q=Promise.resolve(),G=!1,F=()=>{if(!G)G=!0,X.close()};return X.setReceive((O)=>{if(G)return;if(O.length<13||O[0]!==1){F();return}let M=W8(O.subarray(1,13)),T=W8(O.subarray(13));q=q.then(async()=>{if(G)return;try{let V=await crypto.subtle.decrypt({name:"AES-GCM",iv:M},Q,T);Z?.(new Uint8Array(V))}catch{F()}})}),{send(O){if(G)return;let M=W8(O);H=H.then(async()=>{if(G)return;try{let T=crypto.getRandomValues(new Uint8Array(12)),V=W8(T),j=await crypto.subtle.encrypt({name:"AES-GCM",iv:V},Q,M),k=new Uint8Array(j),v=new Uint8Array(13+k.byteLength);v[0]=1,v.set(T,1),v.set(k,13),X.send(v)}catch{F()}})},setReceive(O){Z=O},close(){F()}}}class W${buffer=[];waiters=[];ctrl=new AbortController;cleanup;ended=!1;failure=null;constructor(X){let $=(Q)=>{if(this.ended||this.failure)return;let Z=this.waiters.shift();if(Z){Z.resolve({value:Q,done:!1});return}this.buffer.push(Q)};try{let Q=X($,this.ctrl.signal);if(typeof Q==="function")this.cleanup=Q}catch(Q){this.failure=Q}}[Symbol.asyncIterator](){return{next:async()=>{if(this.buffer.length>0)return{value:this.buffer.shift(),done:!1};if(this.failure)throw this.failure;if(this.ended)return{value:void 0,done:!0};return new Promise((X,$)=>this.waiters.push({resolve:X,reject:$}))},return:async()=>{return this.dispose(),{value:void 0,done:!0}}}}cancel(){this.dispose()}[Symbol.dispose](){this.dispose()}dispose(){if(this.ended)return;this.ended=!0,this.ctrl.abort();try{this.cleanup?.()}catch{}while(this.waiters.length>0)this.waiters.shift().resolve({value:void 0,done:!0})}}var kX=null;function R8(){if(!kX)kX=host.runtime().then((X)=>X.surface());return kX}function c(X){return R8().then(X).catch(($)=>{if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] surface call failed",$);return})}function m(X){return R8().then(X)}class w0{element;onBoundsChange;observer=null;rafId=0;lastRect={x:0,y:0,width:0,height:0};dirty=!1;stopped=!1;constructor(X,$){this.element=X,this.onBoundsChange=$}start(){this.observer=new ResizeObserver(()=>this.markDirty()),this.observer.observe(this.element),this.scheduleFrame()}stop(){if(this.stopped=!0,this.observer?.disconnect(),this.observer=null,this.rafId)cancelAnimationFrame(this.rafId),this.rafId=0}markDirty(){this.dirty=!0}scheduleFrame(){if(this.stopped)return;this.rafId=requestAnimationFrame(()=>{this.flush(),this.scheduleFrame()})}flush(){let X=window.devicePixelRatio||1,$=this.element.getBoundingClientRect(),Q={x:Math.round($.x*X),y:Math.round($.y*X),width:Math.round($.width*X),height:Math.round($.height*X)};if(!this.dirty&&Q.x===this.lastRect.x&&Q.y===this.lastRect.y&&Q.width===this.lastRect.width&&Q.height===this.lastRect.height)return;this.dirty=!1,this.lastRect=Q,this.onBoundsChange(Q)}}class b0 extends HTMLElement{static observedAttributes=["src"];_surfaceId=null;_syncCtrl=null;_initPromise=null;_aborted=!1;_pendingSrc=null;_syncHidden=!1;_userHidden=!1;_layoutObserver=null;_unsubNavigate=null;_activeStreams=[];constructor(){super()}connectedCallback(){this._aborted=!1,this._syncHidden=!1,this._userHidden=!1;let X=new AbortController;this._unsubNavigate=()=>X.abort(),(async()=>{try{let $=await R8();if(X.signal.aborted)return;await this._waitForSurfaceId(X.signal);let Q=this._surfaceId;if(X.signal.aborted||Q==null)return;let Z=$.surfaceEvents({surfaceId:Q});this._activeStreams.push(Z);let H=$.downloadEvents({surfaceId:Q});this._activeStreams.push(H),(async()=>{try{for await(let q of H){if(X.signal.aborted)break;this.dispatchEvent(new CustomEvent("download-event",{detail:q}))}}catch{}})();for await(let q of Z){if(X.signal.aborted)break;this.dispatchEvent(new CustomEvent("surface-event",{detail:q}))}}catch($){if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] surfaceEvents stream failed",$)}})(),this._waitForLayout()}async _waitForSurfaceId(X){while(this._surfaceId==null&&!X.aborted){let $=this._initPromise;if($)try{await $}catch{return}else await new Promise((Q)=>setTimeout(Q,16))}}_waitForLayout(){if(this._layoutObserver)return;let X=()=>{if(!this.isConnected||this._aborted)return!0;let $=this.getBoundingClientRect();if($.width>0&&$.height>0){if(this.getAttribute("src")||this._pendingSrc||"")this.initSurface();return!0}return!1};requestAnimationFrame(()=>{if(X())return;this._layoutObserver=new ResizeObserver(()=>{if(X())this._layoutObserver?.disconnect(),this._layoutObserver=null}),this._layoutObserver.observe(this)})}disconnectedCallback(){this._aborted=!0,this._unsubNavigate?.(),this._unsubNavigate=null;for(let X of this._activeStreams)try{X.cancel?.()}catch{}if(this._activeStreams=[],this._layoutObserver?.disconnect(),this._layoutObserver=null,this._syncCtrl?.stop(),this._syncCtrl=null,this._surfaceId!=null){let X=this._surfaceId;this._surfaceId=null,c(($)=>$.remove({surfaceId:X}))}else if(this._initPromise)this._initPromise.then((X)=>{c(($)=>$.remove({surfaceId:X.surfaceId}))}).catch(()=>{});this._initPromise=null}attributeChangedCallback(X,$,Q){if(X!=="src")return;if(this._surfaceId!=null){let Z=this._surfaceId;c((H)=>H.navigate({surfaceId:Z,url:Q||""}))}else if(this._initPromise)this._pendingSrc=Q||"";else if(this.isConnected&&!this._aborted&&Q)this._waitForLayout()}setHidden(X){this._userHidden=X,this._applySurfaceHidden()}goBack(){let X=this._surfaceId;if(X!=null)c(($)=>$.goBack({surfaceId:X}))}reload(){let X=this._surfaceId;if(X!=null)c(($)=>$.reload({surfaceId:X}))}navigate(X){this.setAttribute("src",X)}async evaluate(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Z)=>Z.evaluate({surfaceId:Q,script:X,frameId:$?.frameId}))}async capabilities(){let X=this._surfaceId;if(X==null)return{evaluate:!1,crossOriginEval:!1,surfaceEvents:!1,nativeInputTrusted:!1,click:!1,type:!1,press:!1,scroll:!1,mouse:!1,dialogs:!1,console:!1,screenshot:!1,accessibilitySnapshot:!1,getBoundingRect:!1,frames:!1,downloads:!1,popups:!1,resolveAndClick:!1};return m(($)=>$.capabilities({surfaceId:X}))}async sendClick(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.click({surfaceId:$,...X}))}async sendType(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.type({surfaceId:$,text:X}))}async sendPress(X,$,Q){let Z=this._surfaceId;if(Z==null)return;await m((H)=>H.press({surfaceId:Z,key:X,modifiers:$,action:Q}))}async sendScroll(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.scroll({surfaceId:$,...X}))}async sendMouse(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.mouse({surfaceId:$,...X}))}async respondToDialog(X,$,Q){let Z=this._surfaceId;if(Z==null)return;await m((H)=>H.respondToDialog({surfaceId:Z,requestId:X,accept:$,text:Q}))}async setDialogTimeout(X){let $=this._surfaceId;if($==null)return;await m((Q)=>Q.setDialogTimeout({surfaceId:$,ms:X}))}async waitForSelector(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.waitForSelector({surfaceId:Q,selector:X,timeoutMs:$}))}async waitForFunction(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.waitForFunction({surfaceId:Q,expression:X,...$}))}async getConsoleBuffer(X){let $=this._surfaceId;if($==null)return[];return await m((Q)=>Q.getConsoleBuffer({surfaceId:$,clear:X?.clear}))??[]}async getNavigationState(){let X=this._surfaceId;if(X==null)return{lastLoadEpoch:0,isLoading:!1,currentUrl:""};return m(($)=>$.getNavigationState({surfaceId:X}))}async accessibilitySnapshot(X){let $=this._surfaceId;if($==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Q)=>Q.accessibilitySnapshot({surfaceId:$,interestingOnly:X?.interestingOnly}))}async getBoundingRect(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.getBoundingRect({surfaceId:Q,selector:X,frameId:$?.frameId}))}async listFrames(){let X=this._surfaceId;if(X==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m(($)=>$.listFrames({surfaceId:X}))}async resolveAndClick(X,$){let Q=this._surfaceId;if(Q==null)return{ok:!1,code:"runtime_error",message:"surface not ready"};return m((Z)=>Z.resolveAndClick({surfaceId:Q,selector:X,...$}))}async setDownloadPolicy(X,$){let Q=this._surfaceId;if(Q==null)return;await c((Z)=>Z.setDownloadPolicy({surfaceId:Q,policy:X,downloadDir:$}))}async waitForDownload(X){let $=this._surfaceId;if($==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Q)=>Q.waitForDownload({surfaceId:$,timeoutMs:X?.timeoutMs}))}async dismissPopup(X){await c(($)=>$.dismissPopup({newSurfaceId:X}))}async extendAdoptionTimeout(X,$){return m((Q)=>Q.extendPopupTimeout({newSurfaceId:X,gracePeriodMs:$}))}async screenshot(X){let $=this._surfaceId;if($==null)return{ok:!1,code:"not_supported",message:"surface not ready"};return m((Q)=>Q.screenshot({surfaceId:$,...X}))}_applySurfaceHidden(){let X=this._surfaceId;if(X==null)return;let $=this._userHidden||this._syncHidden;c((Q)=>Q.setHidden({surfaceId:X,hidden:$}))}_setupSyncCtrl(){this._syncCtrl=new w0(this,(X)=>{let $=this._surfaceId;if($==null)return;if(X.width===0&&X.height===0){if(!this._syncHidden)this._syncHidden=!0,this._applySurfaceHidden();return}if(this._syncHidden)this._syncHidden=!1,this._applySurfaceHidden();c((Z)=>Z.resize({surfaceId:$,x:X.x,y:X.y,w:X.width,h:X.height}))}),this._syncCtrl.start()}initSurface(){if(this._surfaceId!=null||this._initPromise!=null)return;let X=window.devicePixelRatio||1,$=this.getBoundingClientRect(),Q=this.getAttribute("adopt-popup-id"),Z=Q?Number(Q):NaN;if(Number.isFinite(Z)){let G=R8().then(async(F)=>{let O=await F.acceptPopup({newSurfaceId:Z,hostViewId:__buniteWebviewId,bounds:{x:Math.round($.x*X),y:Math.round($.y*X),width:Math.round($.width*X),height:Math.round($.height*X)}});if(!O.ok)throw Error(`acceptPopup failed: ${O.code}: ${O.message}`);return{surfaceId:Z}});this._initPromise=G,G.then((F)=>{if(this._initPromise!==G)return;if(this._aborted){c((O)=>O.remove({surfaceId:F.surfaceId}));return}this._surfaceId=F.surfaceId,this._setupSyncCtrl()}).catch((F)=>{if(globalThis.__BUNITE_DEBUG__)console.warn("[bunite] adopt-popup-id init failed",F);this._initPromise=null});return}let H=this._pendingSrc||this.getAttribute("src")||"";this._pendingSrc=null;let q=R8().then((G)=>G.init({src:H,x:Math.round($.x*X),y:Math.round($.y*X),width:Math.round($.width*X),height:Math.round($.height*X),hidden:this._userHidden}));this._initPromise=q,q.then((G)=>{if(this._initPromise!==q)return;if(this._aborted){c((F)=>F.remove({surfaceId:G.surfaceId}));return}if(this._surfaceId=G.surfaceId,this._userHidden)this._applySurfaceHidden();if(this._pendingSrc!=null){let F=this._pendingSrc;this._pendingSrc=null;let O=this._surfaceId;if(O!=null)c((M)=>M.navigate({surfaceId:O,url:F}))}this._setupSyncCtrl()}).catch(()=>{}).finally(()=>{if(this._initPromise===q)this._initPromise=null})}}if(typeof customElements<"u"){customElements.define("bunite-webview",b0);let X=()=>{c(($)=>$.bringAllVisiblesToFront())};document.addEventListener("pointerdown",X,!0),document.addEventListener("dragstart",()=>{c(($)=>$.setAllPassthrough({passthrough:!0}))},!0),document.addEventListener("dragend",()=>{c(($)=>$.setAllPassthrough({passthrough:!1})),X()},!0)}var yX=null,B8=null;function a8(){if(yX)return Promise.resolve(yX);if(B8)return B8;let X=(async()=>{let $=new WebSocket(`ws://localhost:${__buniteRpcSocketPort}/rpc?webviewId=${__buniteWebviewId}`);$.binaryType="arraybuffer",await new Promise((q,G)=>{$.addEventListener("open",()=>q(),{once:!0}),$.addEventListener("error",()=>G(Error("bunite preload ws connect failed")),{once:!0})});let Q=Uint8Array.from(atob(__buniteSecretKeyBase64),(q)=>q.charCodeAt(0)),Z=await IX(bX($),Q),H=xX({transport:wX(Z),mode:"native",origin:location.origin});return yX=H,H})();return B8=X,X.catch(()=>{if(B8===X)B8=null}),X}var i=window;i.__bunite??={};i.__buniteWebviewId=__buniteWebviewId;i.__buniteRpcSocketPort=__buniteRpcSocketPort;i.host??={};i.host.bootstrap=async(X)=>{return(await a8()).bootstrap(X)};i.host.runtime=async()=>(await a8()).runtime();i.host.releaseRef=async(X)=>{(await a8()).releaseRef(X)};i.host.getConnection=()=>a8();var S0=Symbol.for("bunite.console.buffer"),I0=200,R$=16,B$=50;i[S0]=[];var i8=i[S0];function V$(X){if(typeof X==="string")return X;if(X instanceof Error)return X.stack??X.message;try{return JSON.stringify(X)}catch{return String(X)}}var U8=null,k0=0,T$=1000;function P$(){if(U8)return U8;if(Date.now()<k0)return Promise.reject(Error("reporting cap cooldown"));return U8=(async()=>{return(await i.host.runtime()).reporting()})(),U8.catch(()=>{U8=null,k0=Date.now()+T$}),U8}var T8=[],P8=null;function y0(){if(P8)clearTimeout(P8),P8=null;if(T8.length===0)return;let X=T8;T8=[],P$().then(($)=>$.reportConsoleBatch({entries:X})).catch(()=>{})}function E$(){if(T8.length>=B$){y0();return}if(P8)return;P8=setTimeout(y0,R$)}function C$(){for(let X of["log","warn","error","info","debug"]){let $=console[X].bind(console);console[X]=(...Q)=>{try{$(...Q)}catch{}try{let Z={level:X,args:Q.map(V$),ts:Date.now()};if(i8.push(Z),i8.length>I0)i8.splice(0,i8.length-I0);T8.push(Z),E$()}catch{}}}}C$();var V8=null;function SX(){if(!V8)V8=(async()=>{return await(await(await i.host.runtime()).window()).current()})(),V8.catch(()=>{V8=null});return V8}function v0(X){let $=X instanceof Element?X:null;while($){if($.hasAttribute("data-bunite-no-drag"))return!1;if($.hasAttribute("data-bunite-drag-region"))return!0;$=$.parentElement}return!1}SX();document.addEventListener("mousedown",(X)=>{if(X.button!==0||window.self!==window.top||!v0(X.target))return;SX().then(($)=>$.beginMoveDrag()).catch(()=>{})},!0);document.addEventListener("dblclick",(X)=>{if(X.button!==0||window.self!==window.top||!v0(X.target))return;SX().then(($)=>$.toggleMaximize()).catch(()=>{})},!0);
|
package/src/preload/runtime.ts
CHANGED
|
@@ -163,4 +163,43 @@ function installConsoleProxy() {
|
|
|
163
163
|
|
|
164
164
|
installConsoleProxy();
|
|
165
165
|
|
|
166
|
+
// --- custom titlebar drag region (Tauri-style data attribute) -----------
|
|
167
|
+
// `data-bunite-drag-region` → window move on left mousedown; a nearer
|
|
168
|
+
// `data-bunite-no-drag` ancestor opts out. dblclick → toggle maximize.
|
|
169
|
+
// Data attribute (not `-webkit-app-region` CSS) because that CSS property is
|
|
170
|
+
// not exposed to JS via getComputedStyle.
|
|
171
|
+
let _windowCap: Promise<{ beginMoveDrag(): unknown; toggleMaximize(): unknown }> | null = null;
|
|
172
|
+
function windowCap() {
|
|
173
|
+
if (!_windowCap) {
|
|
174
|
+
_windowCap = (async () => {
|
|
175
|
+
const rt = await (w.host as { runtime(): Promise<any> }).runtime();
|
|
176
|
+
const wc = await rt.window();
|
|
177
|
+
return await wc.current();
|
|
178
|
+
})();
|
|
179
|
+
_windowCap.catch(() => { _windowCap = null; });
|
|
180
|
+
}
|
|
181
|
+
return _windowCap;
|
|
182
|
+
}
|
|
183
|
+
function isDragHit(target: EventTarget | null): boolean {
|
|
184
|
+
let el = target instanceof Element ? target : null;
|
|
185
|
+
while (el) {
|
|
186
|
+
if (el.hasAttribute("data-bunite-no-drag")) return false;
|
|
187
|
+
if (el.hasAttribute("data-bunite-drag-region")) return true;
|
|
188
|
+
el = el.parentElement;
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
// Pre-warm the window cap so the first drag's beginMoveDrag is a single cached
|
|
193
|
+
// call — lazy resolution (bootstrap + window + current) would otherwise miss
|
|
194
|
+
// the drag's first frames while the cursor has already moved.
|
|
195
|
+
void windowCap();
|
|
196
|
+
document.addEventListener("mousedown", (e) => {
|
|
197
|
+
if (e.button !== 0 || window.self !== window.top || !isDragHit(e.target)) return;
|
|
198
|
+
windowCap().then((c) => c.beginMoveDrag()).catch(() => {});
|
|
199
|
+
}, true);
|
|
200
|
+
document.addEventListener("dblclick", (e) => {
|
|
201
|
+
if (e.button !== 0 || window.self !== window.top || !isDragHit(e.target)) return;
|
|
202
|
+
windowCap().then((c) => c.toggleMaximize()).catch(() => {});
|
|
203
|
+
}, true);
|
|
204
|
+
|
|
166
205
|
import "../webview/native";
|
package/src/rpc/framework.ts
CHANGED
|
@@ -1,18 +1,37 @@
|
|
|
1
1
|
import { call, defineCap, stream, cap } from "./schema";
|
|
2
2
|
import type { CapDef } from "./schema";
|
|
3
3
|
|
|
4
|
+
/** Window state for custom-titlebar rendering (max/restore glyph + focus ring). */
|
|
5
|
+
export interface WindowState {
|
|
6
|
+
maximized: boolean;
|
|
7
|
+
minimized: boolean;
|
|
8
|
+
focused: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
4
11
|
export const BrowserWindowCap = defineCap("bunite.BrowserWindow", {
|
|
5
12
|
focus: call<void, void>(),
|
|
6
|
-
close: call<void, void>(),
|
|
13
|
+
close: call<void, void>(), // vetoable — routes through close-requested
|
|
7
14
|
setBounds: call<{ x: number; y: number; w: number; h: number }, void>(),
|
|
8
15
|
setTitle: call<{ title: string }, void>(),
|
|
9
16
|
id: call<void, number>({ idempotent: true }),
|
|
10
17
|
label: call<void, string>({ idempotent: true }),
|
|
18
|
+
minimize: call<void, void>(),
|
|
19
|
+
unminimize: call<void, void>(),
|
|
20
|
+
maximize: call<void, void>(),
|
|
21
|
+
unmaximize: call<void, void>(),
|
|
22
|
+
toggleMaximize: call<void, void>(),
|
|
23
|
+
getState: call<void, WindowState>({ idempotent: true }),
|
|
24
|
+
stateWatch: stream<void, WindowState>(), // emits current state on subscribe, then on change
|
|
25
|
+
// Start an OS window move (Tauri startDragging equiv) — call from a custom
|
|
26
|
+
// titlebar mousedown. Preload auto-calls this for `app-region: drag`; manual
|
|
27
|
+
// callers use it for custom hit-testing. Start-only; native follows the cursor.
|
|
28
|
+
beginMoveDrag: call<void, void>(),
|
|
11
29
|
});
|
|
12
30
|
|
|
13
31
|
export const WindowCap = defineCap("bunite.Window", {
|
|
14
32
|
create: call<WindowCreateOpts, typeof BrowserWindowCap>({ returns: cap(BrowserWindowCap) }),
|
|
15
33
|
list: call<void, typeof BrowserWindowCap>({ returns: cap.array(BrowserWindowCap), idempotent: true }),
|
|
34
|
+
current: call<void, typeof BrowserWindowCap>({ returns: cap(BrowserWindowCap), idempotent: true }),
|
|
16
35
|
focus: call<{ id?: number; label?: string }, void>(),
|
|
17
36
|
close: call<{ id?: number; label?: string }, void>(),
|
|
18
37
|
});
|
package/src/rpc/index.ts
CHANGED
package/src/rpc/peer.ts
CHANGED
|
@@ -56,7 +56,7 @@ export const FIRST_USER_TYPE_ID = 128;
|
|
|
56
56
|
|
|
57
57
|
export const MAX_CAPS_PER_CONNECTION = 1024;
|
|
58
58
|
export const MAX_IN_FLIGHT_CALLS_PER_CONNECTION = 1024;
|
|
59
|
-
/** Client-side LRU cap for revoked cap-ids — prevents unbounded growth on long-lived connections with frequent plugin churn
|
|
59
|
+
/** Client-side LRU cap for revoked cap-ids — prevents unbounded growth on long-lived connections with frequent plugin churn. */
|
|
60
60
|
const REVOKED_CACHE_SIZE = MAX_CAPS_PER_CONNECTION * 4;
|
|
61
61
|
|
|
62
62
|
const DEFAULT_DEADLINE_GRACE_MS = 500;
|