@lobu/runtime-device 24.5.0 → 24.6.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.
Files changed (33) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +32 -17
  3. package/npm-shrinkwrap.json +140 -89
  4. package/package.json +2 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +57 -9
  6. package/vendor/cli/dist/commands/_lib/view-bundler.js +9 -1
  7. package/vendor/cli/dist/connectors/linkedin-identity.ts +43 -0
  8. package/vendor/cli/dist/connectors/linkedin.ts +154 -3
  9. package/vendor/cli/dist/connectors/x-like-follow.ts +329 -0
  10. package/vendor/cli/dist/connectors/x.ts +709 -80
  11. package/vendor/cli/dist/internal/connector-compiler.js +3 -1
  12. package/vendor/cli/dist/runtime-components.json +4 -4
  13. package/vendor/cli/package.json +2 -1
  14. package/vendor/connector-sdk/package.json +1 -1
  15. package/vendor/connector-worker/dist/compile/index.d.ts +4 -3
  16. package/vendor/connector-worker/dist/compile/index.js +6 -3
  17. package/vendor/connector-worker/package.json +1 -1
  18. package/vendor/core/dist/contracts/tools/view-host.d.ts +7 -0
  19. package/vendor/core/dist/contracts/tools/view-host.js +28 -0
  20. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -4
  21. package/vendor/core/dist/contracts/tools/view-runtime.js +19 -7
  22. package/vendor/core/package.json +11 -1
  23. package/vendor/views/dist/api.d.ts +290 -0
  24. package/vendor/views/dist/api.js +714 -0
  25. package/vendor/views/dist/bridge.d.ts +157 -0
  26. package/vendor/views/dist/bridge.js +372 -0
  27. package/vendor/views/dist/components.d.ts +172 -0
  28. package/vendor/views/dist/components.js +376 -0
  29. package/vendor/views/dist/index.d.ts +13 -0
  30. package/vendor/views/dist/index.js +3 -0
  31. package/vendor/views/dist/native.d.ts +327 -0
  32. package/vendor/views/dist/native.js +57 -0
  33. package/vendor/views/package.json +53 -0
@@ -0,0 +1,714 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ import { Component, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { ViewBridge, ViewBridgeError, } from "./bridge.js";
5
+ export function defineView(def) {
6
+ if (!def || typeof def.key !== "string" || def.key.length === 0) {
7
+ throw new Error("defineView({ key, attach, ... }) requires a non-empty key");
8
+ }
9
+ if (!Array.isArray(def.attach)) {
10
+ throw new Error(`defineView("${def.key}") requires attach to be an array`);
11
+ }
12
+ return def;
13
+ }
14
+ const Ctx = createContext(null);
15
+ function useRuntime() {
16
+ const rt = useContext(Ctx);
17
+ if (!rt)
18
+ throw new Error("@lobu/views hooks must run inside mountView()");
19
+ return rt;
20
+ }
21
+ export function useParams() {
22
+ const rt = useRuntime();
23
+ return [rt.params, rt.setParams];
24
+ }
25
+ export function useScope() {
26
+ return useRuntime().scope;
27
+ }
28
+ export function useHost() {
29
+ const rt = useRuntime();
30
+ return {
31
+ connected: rt.connected,
32
+ ready: rt.ready,
33
+ theme: rt.theme,
34
+ openLink: rt.openLink,
35
+ openRecord: rt.openRecord,
36
+ displayMode: rt.displayMode,
37
+ container: rt.container,
38
+ requestDisplayMode: rt.requestDisplayMode,
39
+ };
40
+ }
41
+ /** The workspace root relative links resolve against: the shell's
42
+ * `lobu-workspace` meta, absent outside a server-rendered shell. */
43
+ export function resolveViewHref(href) {
44
+ const base = document
45
+ .querySelector('meta[name="lobu-workspace"]')
46
+ ?.getAttribute("content");
47
+ if (!base)
48
+ return href;
49
+ try {
50
+ return new URL(href, base).href;
51
+ }
52
+ catch {
53
+ return href;
54
+ }
55
+ }
56
+ function resultError(result) {
57
+ if (result.isError !== true)
58
+ return null;
59
+ const content = Array.isArray(result.content) ? result.content : [];
60
+ const text = content
61
+ .map((c) => c && typeof c === "object" && c.type === "text"
62
+ ? String(c.text ?? "")
63
+ : "")
64
+ .join("\n")
65
+ .trim();
66
+ return text || "The host reported a tool error.";
67
+ }
68
+ export function sql(strings, ...values) {
69
+ let text = "";
70
+ strings.forEach((s, i) => {
71
+ text += s;
72
+ if (i < values.length)
73
+ text += escapeLiteral(values[i]);
74
+ });
75
+ return { kind: "sql", text };
76
+ }
77
+ export function escapeLiteral(value) {
78
+ if (value === null || value === undefined)
79
+ return "NULL";
80
+ if (typeof value === "number") {
81
+ if (!Number.isFinite(value))
82
+ throw new Error("sql: only finite numbers can be bound");
83
+ return String(value);
84
+ }
85
+ if (typeof value === "boolean")
86
+ return value ? "TRUE" : "FALSE";
87
+ if (typeof value === "string")
88
+ return `'${value.replaceAll("'", "''")}'`;
89
+ throw new Error("sql: only string, number, boolean, null values can be bound");
90
+ }
91
+ export function tool(name, args = {}) {
92
+ if (!name)
93
+ throw new Error("tool() requires a tool name");
94
+ return { kind: "tool", name, args };
95
+ }
96
+ function parseTextJson(result) {
97
+ const content = Array.isArray(result.content) ? result.content : [];
98
+ for (const c of content) {
99
+ if (!c || typeof c !== "object" || c.type !== "text")
100
+ continue;
101
+ let text = String(c.text ?? "").trim();
102
+ const fence = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
103
+ if (fence?.[1])
104
+ text = fence[1].trim();
105
+ try {
106
+ return JSON.parse(text);
107
+ }
108
+ catch {
109
+ // not JSON — keep looking
110
+ }
111
+ }
112
+ return null;
113
+ }
114
+ /**
115
+ * Read one `useQuery` result. A failed read is an error, never an empty
116
+ * result: `query_sql` answers a rejected statement (unknown table, bad column)
117
+ * with a normal result carrying `error` beside `rows: []`, and `query_sdk`
118
+ * reports a thrown script as `success: false` — both would otherwise render as
119
+ * "no rows". The server's typed code rides along as `errorCode`, and a capped
120
+ * result (`query_sql`'s `has_more`, `query_sdk`'s `return_truncated`) is
121
+ * flagged `truncated` instead of passing as the whole answer, and a
122
+ * `query_sql` cell bounded by its size limits is named in `truncatedColumns`.
123
+ */
124
+ export function queryResult(kind, result) {
125
+ // structuredContent when the tool declares an outputSchema (query_sql,
126
+ // query_sdk, every read tool on MCP hosts); otherwise the text body.
127
+ const sc = (result.structuredContent ??
128
+ parseTextJson(result) ??
129
+ {});
130
+ if (kind === "sql" && typeof sc.error === "string" && sc.error)
131
+ return {
132
+ data: null,
133
+ error: sc.error,
134
+ errorCode: typeof sc.error_code === "string" ? sc.error_code : null,
135
+ truncated: false,
136
+ truncatedColumns: [],
137
+ };
138
+ if (kind === "sdk" && sc.success === false) {
139
+ const e = sc.error;
140
+ const message = typeof e === "string" ? e : e?.message;
141
+ const code = typeof e === "object" ? e?.code : undefined;
142
+ return {
143
+ data: null,
144
+ error: typeof message === "string" && message
145
+ ? message
146
+ : "Query script failed",
147
+ errorCode: typeof code === "string" ? code : null,
148
+ truncated: false,
149
+ truncatedColumns: [],
150
+ };
151
+ }
152
+ // MCP also marks resolved SQL/SDK failures isError; decode their envelopes
153
+ // above before falling back to the host's text and thrown-error metadata.
154
+ const err = resultError(result);
155
+ if (err) {
156
+ const e = sc.error;
157
+ const code = typeof e === "object" ? e?.code : undefined;
158
+ return {
159
+ data: null,
160
+ error: err,
161
+ errorCode: typeof code === "string" ? code : null,
162
+ truncated: false,
163
+ truncatedColumns: [],
164
+ };
165
+ }
166
+ // query_sdk → { success, return_value }, query_sql → { rows }, a named
167
+ // tool → its whole body.
168
+ const data = (kind === "sdk" ? sc.return_value : kind === "tool" ? sc : sc.rows);
169
+ const truncated = kind === "sql"
170
+ ? sc.has_more === true
171
+ : kind === "sdk" && sc.return_truncated != null;
172
+ const truncatedColumns = kind === "sql" && Array.isArray(sc.truncated_columns)
173
+ ? sc.truncated_columns.filter((c) => typeof c === "string")
174
+ : [];
175
+ return {
176
+ data: data ?? null,
177
+ error: null,
178
+ errorCode: null,
179
+ truncated,
180
+ truncatedColumns,
181
+ };
182
+ }
183
+ /**
184
+ * Run a read through the host. `sql\`…\`` → `query_sql`; a string →
185
+ * `query_sdk` script; `tool(name, args)` → that tool; `null` skips. The first
186
+ * fetch waits for the host's first `tool-input`: reads before it run against
187
+ * defaults and double-fetch when the real scope lands.
188
+ */
189
+ export function useQuery(query, options = {}) {
190
+ const live = options.live ?? true;
191
+ const rt = useRuntime();
192
+ const [state, setState] = useState({
193
+ data: null,
194
+ error: null,
195
+ errorCode: null,
196
+ truncated: false,
197
+ truncatedColumns: [],
198
+ loading: query !== null,
199
+ });
200
+ const [tick, setTick] = useState(0);
201
+ // A host data change re-reads the same query in the background: the rows
202
+ // already on screen stay until the fresh ones land, so a live view never
203
+ // flashes its loading state on every write.
204
+ const lastRead = useRef(null);
205
+ // Reads are numbered so a newer read never discards an older one still in
206
+ // flight for the same key: under a steady stream of writes every re-read
207
+ // would be superseded before it answered. Only a key change, or a newer
208
+ // answer already on screen, drops a result.
209
+ const readSeq = useRef(0);
210
+ const shownSeq = useRef(0);
211
+ // A data change while a read is still answering waits for it and then reads
212
+ // once more, so a burst of writes costs one follow-up read instead of one
213
+ // concurrent read per write.
214
+ const reading = useRef(0);
215
+ const owed = useRef(false);
216
+ const [followUp, setFollowUp] = useState(0);
217
+ const key = query === null
218
+ ? null
219
+ : typeof query === "string"
220
+ ? `sdk:${query}`
221
+ : query.kind === "tool"
222
+ ? `tool:${query.name}:${JSON.stringify(query.args)}`
223
+ : `sql:${query.text}`;
224
+ // biome-ignore lint/correctness/useExhaustiveDependencies: key is the stable identity of query (listing query itself refetches every render); rt.callTool is stable; tick, rt.dataVersion and followUp are the intentional refetch triggers.
225
+ useEffect(() => {
226
+ // A skipped query is idle, even when the previous request is in flight.
227
+ if (key === null) {
228
+ lastRead.current = null;
229
+ owed.current = false;
230
+ setState((s) => (s.loading ? { ...s, loading: false } : s));
231
+ return;
232
+ }
233
+ // Queries still wait for the host to seed scope and params.
234
+ if (!rt.ready)
235
+ return;
236
+ // A non-live read ignores data changes; a new key or refetch() still reads.
237
+ if (!live &&
238
+ lastRead.current?.key === key &&
239
+ lastRead.current.tick === tick) {
240
+ return;
241
+ }
242
+ const last = lastRead.current;
243
+ const background = last?.key === key &&
244
+ last.tick === tick &&
245
+ (last.dataVersion !== rt.dataVersion || last.followUp !== followUp);
246
+ lastRead.current = { key, dataVersion: rt.dataVersion, tick, followUp };
247
+ if (background && reading.current !== 0) {
248
+ owed.current = true;
249
+ return;
250
+ }
251
+ const seq = ++readSeq.current;
252
+ reading.current = seq;
253
+ owed.current = false;
254
+ const show = (next) => {
255
+ if (lastRead.current?.key !== key || seq < shownSeq.current)
256
+ return;
257
+ shownSeq.current = seq;
258
+ setState(next);
259
+ };
260
+ const settle = () => {
261
+ if (reading.current !== seq)
262
+ return;
263
+ reading.current = 0;
264
+ if (owed.current && lastRead.current?.key === key) {
265
+ owed.current = false;
266
+ setFollowUp((n) => n + 1);
267
+ }
268
+ };
269
+ if (!background)
270
+ setState((s) => ({ ...s, loading: true }));
271
+ const q = query;
272
+ const call = typeof q === "string"
273
+ ? rt.callTool("query_sdk", { script: q })
274
+ : q.kind === "tool"
275
+ ? rt.callTool(q.name, q.args)
276
+ : rt.callTool("query_sql", { sql: q.text, limit: 500 });
277
+ call
278
+ .then((result) => {
279
+ const out = queryResult(typeof q === "string" ? "sdk" : q.kind === "tool" ? "tool" : "sql", result);
280
+ show({ ...out, loading: false });
281
+ })
282
+ .catch((e) => {
283
+ show({
284
+ data: null,
285
+ error: e instanceof Error ? e.message : String(e),
286
+ errorCode: null,
287
+ truncated: false,
288
+ truncatedColumns: [],
289
+ loading: false,
290
+ });
291
+ })
292
+ .finally(settle);
293
+ }, [key, rt.ready, tick, rt.dataVersion, followUp, live]);
294
+ const refetch = useCallback(() => setTick((t) => t + 1), []);
295
+ return { ...state, refetch };
296
+ }
297
+ /** Mint one id for a deliberate submission, retained by its retry closure. */
298
+ export function mintInteractionId() {
299
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
300
+ return crypto.randomUUID();
301
+ }
302
+ return `${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
303
+ }
304
+ /** Submit a declared action. Failed acknowledgements expose an explicit retry
305
+ * that keeps the original value, event subject and interaction id. */
306
+ export function useAction(name) {
307
+ const rt = useRuntime();
308
+ if (!rt.def.actions?.[name]) {
309
+ throw new Error(`Action "${name}" is not declared on view "${rt.def.key}"`);
310
+ }
311
+ return useCallback(async (value = {}) => {
312
+ if (!rt.ready) {
313
+ return {
314
+ ok: false,
315
+ error: "The host has not supplied the view subject.",
316
+ result: null,
317
+ retry: null,
318
+ };
319
+ }
320
+ let args;
321
+ try {
322
+ // Snapshot JSON before the first send; edits to a form after a failure
323
+ // must not change the meaning of an already accepted submission.
324
+ args = JSON.parse(JSON.stringify({
325
+ view: rt.def.key,
326
+ action: name,
327
+ value,
328
+ ...(rt.scope.event === undefined
329
+ ? {}
330
+ : { scope: { event: rt.scope.event } }),
331
+ interaction_id: mintInteractionId(),
332
+ }));
333
+ }
334
+ catch (error) {
335
+ return {
336
+ ok: false,
337
+ error: error instanceof Error ? error.message : String(error),
338
+ result: null,
339
+ retry: null,
340
+ };
341
+ }
342
+ const submit = async () => {
343
+ try {
344
+ const result = await rt.callTool("invoke_view_action", args);
345
+ const error = resultError(result);
346
+ return {
347
+ ok: !error,
348
+ error,
349
+ result: result.structuredContent ?? null,
350
+ retry: error ? submit : null,
351
+ };
352
+ }
353
+ catch (error) {
354
+ return {
355
+ ok: false,
356
+ error: error instanceof Error ? error.message : String(error),
357
+ result: null,
358
+ retry: submit,
359
+ };
360
+ }
361
+ };
362
+ return submit();
363
+ }, [rt, name]);
364
+ }
365
+ export function defaultsFor(def) {
366
+ const out = {};
367
+ for (const [k, p] of Object.entries(def.params ?? {})) {
368
+ if (p.default !== undefined)
369
+ out[k] = p.default;
370
+ }
371
+ return out;
372
+ }
373
+ export function coerceParams(def, raw) {
374
+ const out = defaultsFor(def);
375
+ if (!raw || typeof raw !== "object")
376
+ return out;
377
+ for (const [k, v] of Object.entries(raw)) {
378
+ const decl = def.params?.[k];
379
+ if (!decl)
380
+ continue; // unknown params ignored (§1.6)
381
+ if (decl.type === "number") {
382
+ const n = typeof v === "number" ? v : Number(v);
383
+ if (Number.isFinite(n))
384
+ out[k] = n;
385
+ }
386
+ else if (decl.type === "boolean") {
387
+ out[k] = v === true || v === "true";
388
+ }
389
+ else if (v !== undefined && v !== null) {
390
+ out[k] = String(v);
391
+ }
392
+ }
393
+ return out;
394
+ }
395
+ export function coerceScope(raw) {
396
+ if (!raw || typeof raw !== "object")
397
+ return {};
398
+ const scope = raw;
399
+ const out = {};
400
+ if (typeof scope.type === "string" && scope.type.length > 0)
401
+ out.type = scope.type;
402
+ if (typeof scope.entity === "number" || typeof scope.entity === "string") {
403
+ out.entity = scope.entity;
404
+ }
405
+ if (typeof scope.event === "number" && Number.isInteger(scope.event)) {
406
+ out.event = scope.event;
407
+ }
408
+ if (scope.collection !== undefined) {
409
+ if (!out.type || out.entity !== undefined || out.event !== undefined) {
410
+ throw new Error("Collection selection requires a type page");
411
+ }
412
+ if (!scope.collection ||
413
+ typeof scope.collection !== "object" ||
414
+ Array.isArray(scope.collection)) {
415
+ throw new Error("Collection selection must be an object");
416
+ }
417
+ // The host validates selection. Preserve it for the validating read API;
418
+ // never drop an unfamiliar filter and silently widen the collection.
419
+ out.collection = scope.collection;
420
+ }
421
+ return out;
422
+ }
423
+ function themeFromContext(ctx) {
424
+ return ctx.theme === "dark" ? "dark" : "light";
425
+ }
426
+ /** `pip` and unknown modes render like a card; only fullscreen is the full view. */
427
+ function displayModeFromContext(ctx) {
428
+ return ctx.displayMode === "fullscreen" ? "fullscreen" : "inline";
429
+ }
430
+ function containerFromContext(ctx) {
431
+ const raw = ctx.containerDimensions;
432
+ if (!raw || typeof raw !== "object")
433
+ return {};
434
+ const out = {};
435
+ for (const key of ["width", "maxWidth", "height", "maxHeight"]) {
436
+ const value = raw[key];
437
+ if (typeof value === "number" && Number.isFinite(value))
438
+ out[key] = value;
439
+ }
440
+ return out;
441
+ }
442
+ function applyTheme(theme) {
443
+ document.documentElement.classList.toggle("dark", theme === "dark");
444
+ document.documentElement.style.colorScheme = theme;
445
+ }
446
+ /**
447
+ * The MCP Apps standard style variables (`McpUiStyleVariableKey`, protocol
448
+ * `2026-01-26`). A host sends any subset in `hostContext.styles.variables`;
449
+ * the shell's tokens (`--fg`, `--muted`, `--border`, `--accent`, the font and
450
+ * radii) derive from them, so a view takes the host's look. Built from the
451
+ * spec's own axes rather than imported: the guest carries no ext-apps code.
452
+ */
453
+ const SEMANTIC = ["primary", "secondary", "tertiary", "inverse", "ghost"];
454
+ const STATUS = ["info", "danger", "success", "warning"];
455
+ const HEADINGS = ["xs", "sm", "md", "lg", "xl", "2xl", "3xl"];
456
+ const HOST_STYLE_KEYS = new Set([
457
+ ...["background", "text", "border"].flatMap((part) => [...SEMANTIC, ...STATUS, "disabled"].map((v) => `--color-${part}-${v}`)),
458
+ ...["primary", "secondary", "inverse", ...STATUS].map((v) => `--color-ring-${v}`),
459
+ "--font-sans",
460
+ "--font-mono",
461
+ ...["normal", "medium", "semibold", "bold"].map((w) => `--font-weight-${w}`),
462
+ ...["size", "line-height"].flatMap((m) => [
463
+ ...["xs", "sm", "md", "lg"].map((s) => `--font-text-${s}-${m}`),
464
+ ...HEADINGS.map((s) => `--font-heading-${s}-${m}`),
465
+ ]),
466
+ ...["xs", "sm", "md", "lg", "xl", "full"].map((r) => `--border-radius-${r}`),
467
+ "--border-width-regular",
468
+ ...["hairline", "sm", "md", "lg"].map((s) => `--shadow-${s}`),
469
+ ]);
470
+ /**
471
+ * Apply the host's standard style variables to the document root. Every
472
+ * standard key is set or cleared from the current context, so a variable a
473
+ * theme switch drops does not linger; anything outside the standard list is
474
+ * ignored, never written.
475
+ */
476
+ function applyHostStyles(ctx) {
477
+ const styles = ctx.styles;
478
+ const variables = styles && typeof styles.variables === "object" && styles.variables
479
+ ? styles.variables
480
+ : {};
481
+ const root = document.documentElement.style;
482
+ for (const key of HOST_STYLE_KEYS) {
483
+ const value = variables[key];
484
+ if (typeof value === "string" && value.trim()) {
485
+ root.setProperty(key, value);
486
+ }
487
+ else {
488
+ root.removeProperty(key);
489
+ }
490
+ }
491
+ }
492
+ /**
493
+ * Contains a render error to the view so the Provider (which owns the host
494
+ * handshake) stays mounted: an uncaught error would unmount it before its
495
+ * effect connects, leaving the host a blank frame with no size and no error.
496
+ * `resetKey` changes when the host delivers scope/params or data changes, so
497
+ * a render that only failed for lack of scope retries once it arrives.
498
+ */
499
+ class RenderBoundary extends Component {
500
+ state = { error: null, resetKey: this.props.resetKey };
501
+ static getDerivedStateFromError(error) {
502
+ return { error: error instanceof Error ? error : new Error(String(error)) };
503
+ }
504
+ static getDerivedStateFromProps(props, state) {
505
+ return props.resetKey === state.resetKey
506
+ ? null
507
+ : { error: null, resetKey: props.resetKey };
508
+ }
509
+ componentDidCatch(error) {
510
+ console.error("[lobu-views] view failed to render", error);
511
+ }
512
+ render() {
513
+ if (!this.state.error)
514
+ return this.props.children;
515
+ return (_jsxs("div", { role: "alert", "data-lobu-render-error": "true", style: { padding: 12, color: "var(--fg)" }, children: ["This view failed to render: ", this.state.error.message] }));
516
+ }
517
+ }
518
+ /**
519
+ * Host bridge provider: seeds scope/params from the first tool-input,
520
+ * exposes reads/actions over tools/call, mirrors params through
521
+ * update-model-context. The server bootstrap renders this around the view's
522
+ * default export; `mountView` does the same for CLI-bundled entries.
523
+ */
524
+ export function Provider({ def, bridge, children, }) {
525
+ const [connected, setConnected] = useState(false);
526
+ const [ready, setReady] = useState(false);
527
+ const [scope, setScope] = useState({});
528
+ const [params, setParamsState] = useState(() => defaultsFor(def));
529
+ const [theme, setTheme] = useState("light");
530
+ const [displayMode, setDisplayMode] = useState("inline");
531
+ const [container, setContainer] = useState({});
532
+ const [dataVersion, setDataVersion] = useState(0);
533
+ const bridgeRef = useRef(bridge ?? null);
534
+ if (bridge)
535
+ bridgeRef.current = bridge;
536
+ if (bridgeRef.current === null)
537
+ bridgeRef.current = new ViewBridge();
538
+ useEffect(() => {
539
+ const b = bridgeRef.current;
540
+ // Unreachable in practice (the body above always installs a bridge
541
+ // before effects run); fail loud instead of dereferencing null.
542
+ if (!b)
543
+ throw new Error("@lobu/views provider has no host bridge");
544
+ const offInput = b.onToolInput((args) => {
545
+ const input = (args ?? {});
546
+ setScope(coerceScope(input.scope));
547
+ setParamsState(coerceParams(def, input.params));
548
+ setReady(true);
549
+ });
550
+ // MCP hosts initially send the permalink arguments. The opening result
551
+ // supplies the exact readable version, including after a supersession.
552
+ const offResult = b.onToolResult((result) => {
553
+ const resolved = result.structuredContent;
554
+ if (resolved?.view === def.key && resolved.scope) {
555
+ setScope(coerceScope(resolved.scope));
556
+ }
557
+ });
558
+ const adoptContext = (ctx) => {
559
+ const next = themeFromContext(ctx);
560
+ setTheme(next);
561
+ applyTheme(next);
562
+ applyHostStyles(ctx);
563
+ setDisplayMode(displayModeFromContext(ctx));
564
+ setContainer(containerFromContext(ctx));
565
+ };
566
+ const offCtx = b.onHostContext(adoptContext);
567
+ const offData = b.onDataChanged(() => setDataVersion((v) => v + 1));
568
+ b.connect()
569
+ .then((ctx) => {
570
+ adoptContext(ctx);
571
+ setConnected(true);
572
+ setReady(b.hasToolInput());
573
+ document.documentElement.setAttribute("data-ready", "true");
574
+ })
575
+ .catch((e) => console.error("[lobu-views] connect failed", e));
576
+ return () => {
577
+ offInput();
578
+ offResult();
579
+ offCtx();
580
+ offData();
581
+ };
582
+ }, [def]);
583
+ // Report the document height so the host can fit the frame. This lives in
584
+ // the provider, not `mountView`: the server bootstrap renders the provider
585
+ // directly, and a frame that never hears a size stays at its minimum height.
586
+ useEffect(() => {
587
+ const b = bridgeRef.current;
588
+ if (!b)
589
+ return;
590
+ const reportSize = () => {
591
+ const doc = document.documentElement;
592
+ doc.setAttribute("data-mounted", "true");
593
+ const prev = doc.style.height;
594
+ doc.style.height = "max-content";
595
+ const height = Math.ceil(doc.getBoundingClientRect().height);
596
+ doc.style.height = prev;
597
+ b.notifySize(Math.ceil(window.innerWidth), height);
598
+ };
599
+ reportSize();
600
+ if (typeof ResizeObserver === "undefined")
601
+ return;
602
+ const observer = new ResizeObserver(reportSize);
603
+ observer.observe(document.documentElement);
604
+ observer.observe(document.body);
605
+ return () => observer.disconnect();
606
+ }, []);
607
+ const setParams = useCallback((patch) => {
608
+ setParamsState((prev) => {
609
+ const next = coerceParams(def, { ...prev, ...patch });
610
+ const b = bridgeRef.current;
611
+ if (b) {
612
+ b.updateModelContext({ view: def.key, params: next }).catch(() => {
613
+ /* host without update-model-context: params stay frame-local */
614
+ });
615
+ }
616
+ return next;
617
+ });
618
+ }, [def]);
619
+ const callTool = useCallback(async (name, args) => {
620
+ const b = bridgeRef.current;
621
+ if (!b?.isConnected()) {
622
+ // No handshake yet — fail loud instead of queueing into a dead host.
623
+ throw new Error("Not connected to a host");
624
+ }
625
+ return b.callTool(name, args);
626
+ }, []);
627
+ const openLink = useCallback(async (url) => {
628
+ const b = bridgeRef.current;
629
+ if (!b?.isConnected())
630
+ throw new Error("Not connected to a host");
631
+ const error = resultError(await b.openLink(resolveViewHref(url)));
632
+ if (error)
633
+ throw new Error(error);
634
+ }, []);
635
+ const openRecord = useCallback(async (record, options) => {
636
+ const b = bridgeRef.current;
637
+ if (!b?.isConnected())
638
+ throw new Error("Not connected to a host");
639
+ try {
640
+ return await b.openRecord(record, options?.mode ?? "peek");
641
+ }
642
+ catch (error) {
643
+ // Only an unsupported extension falls back. A host refusal stays a refusal.
644
+ if (!(error instanceof ViewBridgeError) || error.code !== -32601)
645
+ throw error;
646
+ }
647
+ const response = await b.callTool("manage_entity", {
648
+ ...record,
649
+ action: "get",
650
+ });
651
+ const error = resultError(response);
652
+ if (error)
653
+ throw new Error(error);
654
+ const result = (response.structuredContent ??
655
+ parseTextJson(response));
656
+ if (!result?.entity?.view_url)
657
+ throw new Error("The host did not return a record URL.");
658
+ const failed = resultError(await b.openLink(result.entity.view_url));
659
+ if (failed)
660
+ throw new Error(failed);
661
+ return { mode: "page" };
662
+ }, []);
663
+ const requestDisplayMode = useCallback(async (mode) => {
664
+ const b = bridgeRef.current;
665
+ if (!b?.isConnected())
666
+ throw new Error("Not connected to a host");
667
+ const granted = await b.requestDisplayMode(mode);
668
+ return granted === "fullscreen" ? "fullscreen" : "inline";
669
+ }, []);
670
+ const value = useMemo(() => ({
671
+ def,
672
+ connected,
673
+ ready,
674
+ scope,
675
+ params,
676
+ setParams,
677
+ theme,
678
+ dataVersion,
679
+ callTool,
680
+ openLink,
681
+ openRecord,
682
+ displayMode,
683
+ container,
684
+ requestDisplayMode,
685
+ }), [
686
+ def,
687
+ connected,
688
+ ready,
689
+ scope,
690
+ params,
691
+ setParams,
692
+ theme,
693
+ dataVersion,
694
+ callTool,
695
+ openLink,
696
+ openRecord,
697
+ displayMode,
698
+ container,
699
+ requestDisplayMode,
700
+ ]);
701
+ // A host-resolved replacement is a new form, including in MCP hosts that
702
+ // keep the iframe mounted while delivering the opening result.
703
+ return (_jsx(Ctx.Provider, { value: value, children: _jsx(RenderBoundary, { resetKey: `${ready}:${JSON.stringify(scope)}:${JSON.stringify(params)}:${dataVersion}`, children: children }) }, scope.event ?? "unbound"));
704
+ }
705
+ /** Entry point the compiled bundle calls once. Mounts the component into
706
+ * `#root` and connects to the host. */
707
+ export function mountView(def, Component, opts) {
708
+ const valid = defineView(def);
709
+ const el = document.getElementById("root");
710
+ if (!el)
711
+ throw new Error("#root missing in view shell");
712
+ createRoot(el).render(_jsx(Provider, { def: valid, bridge: opts?.bridge, children: _jsx(Component, {}) }));
713
+ }
714
+ //# sourceMappingURL=api.js.map