skybridge 0.36.3 → 1.0.1

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/README.md CHANGED
@@ -1,153 +1,152 @@
1
- <div align="center">
2
-
3
- <img alt="Skybridge" src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/github-banner.png" width="100%">
4
-
5
- <br />
6
-
7
- **Build ChatGPT & MCP Apps. The Modern TypeScript Way.**
8
-
9
- The fullstack TypeScript framework for AI-embedded views.<br />
10
- **Type-safe. React-powered. Platform-agnostic.**
11
-
12
- <br />
13
-
14
- [![NPM Version](https://img.shields.io/npm/v/skybridge?color=e90060&style=for-the-badge)](https://www.npmjs.com/package/skybridge)
15
- [![NPM Downloads](https://img.shields.io/npm/dm/skybridge?color=e90060&style=for-the-badge)](https://www.npmjs.com/package/skybridge)
16
- [![GitHub License](https://img.shields.io/github/license/alpic-ai/skybridge?color=e90060&style=for-the-badge)](https://github.com/alpic-ai/skybridge/blob/main/LICENSE)
17
-
18
- <br />
19
-
20
- [Documentation](https://docs.skybridge.tech) · [Quick Start](https://docs.skybridge.tech/quickstart/create-new-app) · [Showcase](https://docs.skybridge.tech/showcase)
21
-
22
- </div>
23
-
24
- <br />
25
-
26
- ## Why Skybridge?
27
-
28
- ChatGPT Apps and MCP Apps let you embed **rich, interactive UIs** directly in AI conversations. But the raw SDKs are low-level—no hooks, no type safety, no dev tools, and no HMR.
29
-
30
- **Skybridge fixes that.**
31
-
32
- | | |
33
- |:--|:--|
34
- | 🌐 **Write once, run everywhere** Skybridge works seamlessly with ChatGPT (Apps SDK) and MCP-compatible clients. | **End-to-End Type Safety** — tRPC-style inference from server to view. Autocomplete everywhere. |
35
- | 🔄 **View-to-Model Sync** — Keep the model aware of UI state with `data-llm`. Dual surfaces, one source of truth. | ⚒️ **React Query-style Hooks** — `isPending`, `isError`, callbacks. State management you already know. |
36
- | 👨‍💻 **Full dev environment** — HMR, debug traces, and local devtools. | 📦 **Showcase Examples** — Production-ready examples to learn from and build upon. |
37
-
38
- <br />
39
-
40
- ## 🚀 Get Started
41
-
42
- **Create a new app:**
43
-
1
+ # Skybridge - the MCP Apps framework
2
+
3
+ <p align="center">
4
+ <a href="https://docs.skybridge.tech">
5
+ <picture>
6
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/skybridge-readme-banner-dark.png" />
7
+ <img alt="Skybridge, the full-stack React framework for MCP apps and MCP servers" src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/skybridge-readme-banner-light.png" width="100%" />
8
+ </picture>
9
+ </a>
10
+ </p>
11
+
12
+ <p align="center">
13
+ <strong>The full-stack React framework for MCP Apps and MCP Servers.</strong>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://docs.skybridge.tech">Documentation</a> ·
18
+ <a href="https://docs.skybridge.tech/quickstart/create-new-app">Quickstart</a> ·
19
+ <a href="https://github.com/alpic-ai/skybridge/tree/main/examples">Examples</a>
20
+ </p>
21
+
22
+ <p align="center">
23
+ <a href="https://www.npmjs.com/package/skybridge"><picture><source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/v/skybridge?color=77F5EE&amp;labelColor=161B22&amp;style=for-the-badge"><img alt="npm version" src="https://img.shields.io/npm/v/skybridge?color=E3FAF7&amp;labelColor=F6F8FA&amp;style=for-the-badge"></picture></a>
24
+ <a href="https://www.npmjs.com/package/skybridge"><picture><source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/dm/skybridge?color=D7FFC8&amp;labelColor=161B22&amp;style=for-the-badge"><img alt="npm downloads" src="https://img.shields.io/npm/dm/skybridge?color=E8FBD9&amp;labelColor=F6F8FA&amp;style=for-the-badge"></picture></a>
25
+ <a href="https://discord.com/invite/gNAazGueab"><picture><source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/badge/Discord-community-77F5EE?style=for-the-badge&amp;logo=discord&amp;logoColor=77F5EE&amp;labelColor=161B22"><img alt="Discord community" src="https://img.shields.io/badge/Discord-community-E3FAF7?style=for-the-badge&amp;logo=discord&amp;logoColor=5865F2&amp;labelColor=F6F8FA"></picture></a>
26
+ <a href="https://github.com/alpic-ai/skybridge/blob/main/LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/github/license/alpic-ai/skybridge?color=D7FFC8&amp;labelColor=161B22&amp;style=for-the-badge"><img alt="License: MIT" src="https://img.shields.io/github/license/alpic-ai/skybridge?color=E8FBD9&amp;labelColor=F6F8FA&amp;style=for-the-badge"></picture></a>
27
+ </p>
28
+
29
+ ## About Skybridge
30
+
31
+ Skybridge helps developers build type-safe MCP apps for Claude, ChatGPT and other UI-enabled MCP clients, with a complete set of tooling designed for both humans and agents.
32
+
33
+ Why? MCP apps extend the [Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro) with **rich, interactive UI views** rendered from MCP servers. Conversational apps need seamless interaction between the user, the UI, and the model. This means new UX patterns, developer tooling, and abstractions.
34
+ Plus, the raw SDKs are low-level: no hooks, type safety, HMR, etc.
35
+
36
+ That's why we built *Skybridge*.
37
+
38
+ Features include:
39
+
40
+ - **Delightful dev environment**: Skybridge provides a dev server with a local emulator, hot module reload, and a permanent tunnel to connect your local app to Claude and ChatGPT.
41
+ - **Write once, run everywhere**: the framework abstracts implementation differences between MCP clients, so your app runs seamlessly in Claude, ChatGPT, VSCode, and any other MCP apps compatible client.
42
+ - **Agent-ready**: powerful skills, CLI, and programmatic dev tool APIs, everything your coding agent needs to build MCP apps end-to-end.
43
+ - **Type-safe end-to-end**: tRPC-style inference from MCP server tool definition to React view for type safety from server to frontend.
44
+ - **React-first**: Intuitive React Query-style hooks, with advanced state management.
45
+ - **Example library**: get started quickly with ChatGPT- and Claude-ready app examples for ecommerce, travel, SaaS, and more.
46
+
47
+ They chose to build their MCP apps with Skybridge:
48
+
49
+ <p align="center">
50
+ <a href="https://www.datadoghq.com"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/datadog-dark.svg"><img src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/datadog-light.svg" alt="Datadog" height="24"></picture></a>
51
+ &nbsp;&nbsp;
52
+ <a href="https://bitmovin.com"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/bitmovin-dark.svg"><img src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/bitmovin-light.svg" alt="Bitmovin" height="22"></picture></a>
53
+ &nbsp;&nbsp;
54
+ <a href="https://www.evaneos.com"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/evaneos-dark.svg"><img src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/evaneos-light.svg" alt="Evaneos" height="18"></picture></a>
55
+ &nbsp;&nbsp;
56
+ <a href="https://www.touchstream.media"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/touchstream-dark.svg"><img src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/touchstream-light.svg" alt="Touchstream" height="24"></picture></a>
57
+ &nbsp;&nbsp;
58
+ <a href="https://www.cottages.com"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/cottages-dark.svg"><img src="https://raw.githubusercontent.com/alpic-ai/skybridge/main/docs/images/user-logos/cottages-light.svg" alt="Cottages.com" height="24"></picture></a>
59
+ </p>
60
+
61
+ ## Get started
62
+
63
+ **For agents**
64
+
65
+ Install our [skill](https://docs.skybridge.tech/devtools/skills) for building MCP apps and ChatGPT apps:
44
66
  ```bash
45
- npm create skybridge@latest
67
+ npx skills add alpic-ai/skybridge -s skybridge
46
68
  ```
69
+ Once installed, ask your agent "What skills do you have?" to confirm, then try:
47
70
 
48
- **Or add to an existing project:**
71
+ - _Create a new MCP app_
72
+ - _Migrate my MCP server to the Skybridge framework_
73
+ - _Add a new view to my MCP app_
49
74
 
75
+ **For humans**
76
+
77
+ Bootstrap a new project with:
50
78
  ```bash
51
- npm i skybridge
52
- yarn add skybridge
53
- pnpm add skybridge
54
- bun add skybridge
55
- deno add skybridge
79
+ npm create skybridge@latest my-app
56
80
  ```
81
+ For full install instructions, read our [**Quickstart guide**](https://docs.skybridge.tech/quickstart/create-new-app).
57
82
 
58
- <div align="center">
59
-
60
- **👉 [Read the Docs](https://docs.skybridge.tech) 👈**
61
-
62
- </div>
83
+ ## Documentation
63
84
 
64
- <br />
85
+ The [Skybridge documentation](https://docs.skybridge.tech) covers the full lifecycle of building MCP Apps:
65
86
 
66
- ## 📦 Architecture
87
+ - [Fundamentals](https://docs.skybridge.tech/fundamentals): understand MCP Apps, ChatGPT Apps, and how Skybridge bridges both runtimes.
88
+ - [Core concepts](https://docs.skybridge.tech/concepts): learn about server <> model <> UI data flows, LLM context sync, type safety, and instant local iteration with our devtools.
89
+ - [Guides](https://docs.skybridge.tech/guides/fetching-data): build real app behavior with tools, views, state, and model communication.
90
+ - [API Reference](https://docs.skybridge.tech/api-reference): browse our MCP server APIs, React hooks, CLI commands, and runtime compatibility.
67
91
 
68
- Skybridge is a fullstack framework with unified server and client modules:
92
+ ## Deploy
69
93
 
70
- - **`skybridge/server`** Define tools and views with full type inference. Extends the MCP SDK.
71
- - **`skybridge/web`** — React hooks that consume your server types. Works with Apps SDK (ChatGPT) and MCP Apps.
72
- - **Dev Environment** — Vite plugin with HMR, DevTools emulator, and optimized builds.
94
+ Deploy Skybridge apps instantly on [Alpic](https://alpic.ai) for scalable hosting, MCP-specific analytics, permanent tunneling, app store compliance auditing and submission help. You can also self-host on any Node.js-compatible platform.
73
95
 
74
- ### Server
96
+ See our [deployment guide](https://docs.skybridge.tech/quickstart/deploy) for the full production path.
75
97
 
76
- ```ts
77
- import { McpServer } from "skybridge/server";
98
+ ## Community & Contributing
78
99
 
79
- server.registerView("flights", {}, {
80
- inputSchema: { destination: z.string() },
81
- }, async ({ destination }) => {
82
- const flights = await searchFlights(destination);
83
- return { structuredContent: { flights } };
84
- });
85
- ```
86
-
87
- ### View
88
-
89
- ```tsx
90
- import { useToolInfo } from "skybridge/web";
91
-
92
- function FlightsView() {
93
- const { output } = useToolInfo();
94
-
95
- return output.structuredContent.flights.map(flight =>
96
- <FlightCard key={flight.id} flight={flight} />
97
- );
98
- }
99
- ```
100
+ We'd love your help improving Skybridge. Here are a few ways to get involved:
100
101
 
101
- <br />
102
+ - **Bugs**: If you run into a bug or unexpected behavior, open a [GitHub Issue](https://github.com/alpic-ai/skybridge/issues) with a clear reproduction.
103
+ - **Questions and ideas**: Need help building with Skybridge or have ideas to improve the framework, docs, examples, or developer experience? [Open an issue](https://github.com/alpic-ai/skybridge/issues) or share them on our [Discord](https://discord.com/invite/gNAazGueab).
104
+ - **Pull requests**: For code or documentation changes, read the [Contributing Guide](https://github.com/alpic-ai/skybridge/blob/main/CONTRIBUTING.md) before opening a PR.
102
105
 
103
- ## 🎯 Features at a Glance
106
+ Skybridge is released under the [MIT License](https://github.com/alpic-ai/skybridge/blob/main/LICENSE).
104
107
 
105
- - **Live Reload** — Vite HMR. See changes instantly without reinstalling.
106
- - **Typed Hooks** — Full autocomplete for tools, inputs, outputs.
107
- - **View → Tool Calls** — Trigger server actions from UI.
108
- - **Dual Surface Sync** — Keep model aware of what users see with `data-llm`.
109
- - **React Query-style API** — `isPending`, `isError`, callbacks.
110
- - **Platform Agnostic** — Works with ChatGPT (Apps SDK) and MCP Apps clients (Goose, VSCode, etc.).
111
- - **MCP Compatible** — Extends the official SDK. Works with any MCP client.
108
+ ### Contributors
112
109
 
113
- <br />
110
+ Built and maintained with ❤️ by [Harijoe](https://github.com/harijoe), [Fred Barthelet](https://github.com/fredericbarthelet), and the [Alpic](https://alpic.ai) team.
114
111
 
115
- ## 📖 Showcase
112
+ <a href="https://github.com/alpic-ai/skybridge/graphs/contributors">
113
+ <img src="https://contrib.rocks/image?repo=alpic-ai/skybridge" alt="Skybridge contributors">
114
+ </a>
116
115
 
117
- Explore production-ready examples:
116
+ ## Example templates
118
117
 
119
- | Example | Description | Demo | Code |
120
- |------------------------|----------------------------------------------------------------------------------|-----------------------------------------------------|-------------------------------------------------------------------------------------|
121
- | **Awaze — Cottage Search** | Holiday cottage search and booking experience — browse properties, filter by location, and explore availability | [Try Demo](https://mcp.cottages.com/try) | — |
122
- | **Capitals Explorer** | Interactive world map with geolocation and Wikipedia integration | [Try Demo](https://capitals.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/capitals) |
123
- | **Ecommerce Carousel** | Product carousel with cart, localization, and modals | [Try Demo](https://ecommerce.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/ecom-carousel) |
124
- | **Everything** | Comprehensive playground showcasing all hooks and features | [Try Demo](https://everything.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/everything) |
125
- | **Investigation Game** | Interactive murder mystery game with multi-screen gameplay and dynamic story progression | [Try Demo](https://investigation-game.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/investigation-game) |
126
- | **Productivity** | Data visualization dashboard demonstrating Skybridge capabilities for MCP Apps | [Try Demo](https://productivity.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/productivity) |
127
- | **Time's Up** | Word-guessing party game where the user gives hints and the AI tries to guess the secret word | [Try Demo](https://times-up.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/times-up) |
128
- | **Lumo — Interactive AI Tutor** | Adaptive educational tutor with Mermaid.js diagrams, mind maps, quizzes, and fill-in-the-blank exercises | [Try Demo](https://lumo-mcp-app-39519fdd.alpic.live/try) | [View Code](https://github.com/connorads/lumo-mcp-app) |
129
- | **Auth — Auth0** | Full OAuth authentication with Auth0 and personalized coffee shop search | — | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-auth0) |
130
- | **Auth — Clerk** | Full OAuth authentication with Clerk and personalized coffee shop search | — | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-clerk) |
131
- | **Auth — Stytch** | Full OAuth authentication with Stytch and personalized coffee shop search | — | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-stytch) |
132
- | **Auth — WorkOS AuthKit** | Full OAuth authentication with WorkOS AuthKit and personalized coffee shop search | — | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-workos) |
133
- | **Flight Booking** | Flight booking carousel with dynamic search and booking flow | [Try Demo](https://flight-booking.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/flight-booking) |
134
- | **Generative UI** | Dynamic UI generation using json-render and Skybridge | [Try Demo](https://generative-ui.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/generative-ui) |
135
- | **Manifest Starter** | Starter app with Manifest UI agentic components out-of-the-box | [Try Demo](https://manifest-ui.skybridge.tech/try) | [View Code](https://github.com/alpic-ai/skybridge/tree/main/examples/manifest-ui) |
118
+ Explore all our example templates in the [Examples](https://docs.skybridge.tech/examples) section of the documentation.
136
119
 
137
- See all examples in the [Showcase](https://docs.skybridge.tech/showcase) or browse the [examples/](examples/) directory.
120
+ ### Basic
138
121
 
139
- <br />
122
+ | Preview | App | Description | Demo | Code |
123
+ | --- | --- | --- | --- | --- |
124
+ | <img src="docs/images/showcase-example.png" alt="Everything" width="160" /> | Everything | Comprehensive playground app showcasing all Skybridge hooks and features. | [Try Demo](https://everything.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/everything) |
140
125
 
141
- <div align="center">
126
+ ### Use cases
142
127
 
143
- [![GitHub Discussions](https://img.shields.io/badge/Discussions-Ask%20Questions-blue?style=flat-square&logo=github)](https://github.com/alpic-ai/skybridge/discussions)
144
- [![GitHub Issues](https://img.shields.io/badge/Issues-Report%20Bugs-red?style=flat-square&logo=github)](https://github.com/alpic-ai/skybridge/issues)
145
- [![Discord](https://img.shields.io/badge/Discord-Chat-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.com/invite/gNAazGueab)
128
+ | Preview | App | Description | Demo | Code |
129
+ | --- | --- | --- | --- | --- |
130
+ | <img src="docs/images/showcase-capitals.png" alt="Capitals Explorer" width="160" /> | Capitals Explorer | Interactive world map with geolocation, country information, and dynamic capital exploration. | [Try Demo](https://capitals.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/capitals) |
131
+ | <img src="docs/images/showcase-flight-booking.png" alt="Flight Booking" width="160" /> | Flight Booking | Flight search carousel with route details, pricing comparison, and external booking. | [Try Demo](https://flight-booking.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/flight-booking) |
132
+ | <img src="docs/images/showcase-ecommerce.png" alt="Ecommerce Carousel" width="160" /> | Ecommerce Carousel | Product carousel with persistent cart, localization, theme switching, and modal dialogs. | [Try Demo](https://ecommerce.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/ecom-carousel) |
133
+ | <img src="docs/images/showcase-investigation-game.png" alt="Investigation Game" width="160" /> | Investigation Game | Multi-screen mystery game with fullscreen mode, dynamic story progression and context asynchronicity demonstration | [Try Demo](https://investigation-game.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/investigation-game) |
134
+ | <img src="docs/images/showcase-productivity.png" alt="Productivity" width="160" /> | Productivity | Interactive analytics dashboard with charts, theme adaptation, localization, fullscreen mode, and bidirectional tool calls. | [Try Demo](https://productivity.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/productivity) |
135
+ | <img src="docs/images/showcase-times-up.png" alt="Time's Up" width="160" /> | Time's Up | Word-guessing party game where the user gives hints and the AI tries to guess. | [Try Demo](https://times-up.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/times-up) |
136
+ | <img src="docs/images/showcase-lumo.png" alt="Lumo Interactive AI Tutor" width="160" /> | Lumo — Interactive AI Tutor | Adaptive tutor with Mermaid diagrams, mind maps, quizzes, and fill-in-the-blank exercises. | [Try Demo](https://lumo-mcp-app-39519fdd.alpic.live/try) | [View code](https://github.com/connorads/lumo-mcp-app) |
146
137
 
147
- See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions
138
+ ### Auth
148
139
 
149
- <br />
140
+ | Preview | Provider | Description | Code |
141
+ | --- | --- | --- | --- |
142
+ | <img src="docs/images/showcase-clerk.png" alt="Auth Clerk" width="160" /> | Clerk | Full OAuth authentication with Clerk and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-clerk) |
143
+ | <img src="docs/images/showcase-workos.png" alt="Auth WorkOS AuthKit" width="160" /> | WorkOS AuthKit | Full OAuth authentication with WorkOS AuthKit and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-workos) |
144
+ | <img src="docs/images/showcase-stytch.png" alt="Auth Stytch" width="160" /> | Stytch | Full OAuth authentication with Stytch and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-stytch) |
145
+ | <img src="docs/images/showcase-auth0.png" alt="Auth Auth0" width="160" /> | Auth0 | Full OAuth authentication with Auth0 and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-auth0) |
150
146
 
151
- **[MIT License](LICENSE)** · Made with ❤️ by **[Alpic](https://alpic.ai)**
147
+ ### UI and component libraries
152
148
 
153
- </div>
149
+ | Preview | App | Description | Demo | Code |
150
+ | --- | --- | --- | --- | --- |
151
+ | <img src="docs/images/showcase-manifest-ui.png" alt="Manifest UI" width="160" /> | Manifest UI | Agentic component library example for rich AI-powered experiences. | [Try Demo](https://manifest-ui.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/manifest-ui) |
152
+ | <img src="docs/images/showcase-generative-ui.png" alt="Generative UI" width="160" /> | Generative UI | LLM-generated dynamic UIs with json-render and 36 pre-built shadcn/ui components. | [Try Demo](https://generative-ui.skybridge.tech/try) | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/generative-ui) |
@@ -1,4 +1,5 @@
1
1
  import type { Plugin } from "vite";
2
+ export declare function isCssRequest(id: string): boolean;
2
3
  /**
3
4
  * Transforms asset import paths to resolve at runtime via `window.skybridge.serverUrl`,
4
5
  * so they work both locally and behind tunnels.
@@ -1,3 +1,10 @@
1
+ // Mirrors Vite's own `isCSSRequest`: matches the css family of extensions
2
+ // either at the end of the id or right before the query string. Catches both
3
+ // plain `.css` requests and SFC style blocks (e.g. `Foo.vue?vue&type=style&lang.css`).
4
+ const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
5
+ export function isCssRequest(id) {
6
+ return CSS_LANGS_RE.test(id);
7
+ }
1
8
  /**
2
9
  * Transforms asset import paths to resolve at runtime via `window.skybridge.serverUrl`,
3
10
  * so they work both locally and behind tunnels.
@@ -15,10 +22,18 @@ export function assetBaseUrlTransform(code) {
15
22
  export function assetBaseUrlTransformPlugin() {
16
23
  return {
17
24
  name: "asset-base-url-transform",
18
- transform(code) {
25
+ transform(code, id) {
19
26
  if (!code) {
20
27
  return null;
21
28
  }
29
+ // Vite serves CSS modules as JS that embeds the stylesheet as a string
30
+ // literal. Rewriting `url("/foo.woff2")` inside that string to a JS
31
+ // concatenation expression produces invalid CSS once it lands in a
32
+ // <style> tag. CSS asset URLs are already handled at build time by
33
+ // `experimental.renderBuiltUrl`, so skip CSS requests here.
34
+ if (isCssRequest(id)) {
35
+ return null;
36
+ }
22
37
  const transformedCode = assetBaseUrlTransform(code);
23
38
  if (transformedCode === code) {
24
39
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"asset-base-url-transform-plugin.js","sourceRoot":"","sources":["../../src/server/asset-base-url-transform-plugin.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,MAAM,kBAAkB,GACtB,4GAA4G,CAAC;IAE/G,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE;QACpE,OAAO,0CAA0C,SAAS,GAAG,CAAC;IAChE,CAAC,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO;QACL,IAAI,EAAE,0BAA0B;QAChC,SAAS,CAAC,IAAI;YACZ,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,OAAO,IAAI,CAAC;YACd,CAAC;YAED,MAAM,eAAe,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;YAEpD,IAAI,eAAe,KAAK,IAAI,EAAE,CAAC;gBAC7B,OAAO,IAAI,CAAC;YACd,CAAC;YAED,OAAO;gBACL,IAAI,EAAE,eAAe;gBACrB,GAAG,EAAE,IAAI;aACV,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Plugin } from \"vite\";\n\n/**\n * Transforms asset import paths to resolve at runtime via `window.skybridge.serverUrl`,\n * so they work both locally and behind tunnels.\n */\nexport function assetBaseUrlTransform(code: string): string {\n const assetStringPattern =\n /(?<!\\bfrom\\s)(?<!https?:\\/\\/)([\"'`])(\\/[^\"'`]+\\.(svg|png|jpeg|jpg|gif|webp|mp3|mp4|woff|woff2|ttf|eot))\\1/g;\n\n code = code.replace(assetStringPattern, (_match, _quote, assetPath) => {\n return `(window.skybridge?.serverUrl ?? \"\") + \"${assetPath}\"`;\n });\n\n return code;\n}\n\n/**\n * Vite plugin that transforms asset import paths to resolve at runtime via `window.skybridge.serverUrl`.\n */\nexport function assetBaseUrlTransformPlugin(): Plugin {\n return {\n name: \"asset-base-url-transform\",\n transform(code) {\n if (!code) {\n return null;\n }\n\n const transformedCode = assetBaseUrlTransform(code);\n\n if (transformedCode === code) {\n return null;\n }\n\n return {\n code: transformedCode,\n map: null,\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"asset-base-url-transform-plugin.js","sourceRoot":"","sources":["../../src/server/asset-base-url-transform-plugin.ts"],"names":[],"mappings":"AAEA,0EAA0E;AAC1E,6EAA6E;AAC7E,uFAAuF;AACvF,MAAM,YAAY,GAChB,6DAA6D,CAAC;AAEhE,MAAM,UAAU,YAAY,CAAC,EAAU;IACrC,OAAO,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC/B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,MAAM,kBAAkB,GACtB,4GAA4G,CAAC;IAE/G,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE;QACpE,OAAO,0CAA0C,SAAS,GAAG,CAAC;IAChE,CAAC,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO;QACL,IAAI,EAAE,0BAA0B;QAChC,SAAS,CAAC,IAAI,EAAE,EAAE;YAChB,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,OAAO,IAAI,CAAC;YACd,CAAC;YAED,uEAAuE;YACvE,oEAAoE;YACpE,mEAAmE;YACnE,mEAAmE;YACnE,4DAA4D;YAC5D,IAAI,YAAY,CAAC,EAAE,CAAC,EAAE,CAAC;gBACrB,OAAO,IAAI,CAAC;YACd,CAAC;YAED,MAAM,eAAe,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;YAEpD,IAAI,eAAe,KAAK,IAAI,EAAE,CAAC;gBAC7B,OAAO,IAAI,CAAC;YACd,CAAC;YAED,OAAO;gBACL,IAAI,EAAE,eAAe;gBACrB,GAAG,EAAE,IAAI;aACV,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Plugin } from \"vite\";\n\n// Mirrors Vite's own `isCSSRequest`: matches the css family of extensions\n// either at the end of the id or right before the query string. Catches both\n// plain `.css` requests and SFC style blocks (e.g. `Foo.vue?vue&type=style&lang.css`).\nconst CSS_LANGS_RE =\n /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\\?)/;\n\nexport function isCssRequest(id: string): boolean {\n return CSS_LANGS_RE.test(id);\n}\n\n/**\n * Transforms asset import paths to resolve at runtime via `window.skybridge.serverUrl`,\n * so they work both locally and behind tunnels.\n */\nexport function assetBaseUrlTransform(code: string): string {\n const assetStringPattern =\n /(?<!\\bfrom\\s)(?<!https?:\\/\\/)([\"'`])(\\/[^\"'`]+\\.(svg|png|jpeg|jpg|gif|webp|mp3|mp4|woff|woff2|ttf|eot))\\1/g;\n\n code = code.replace(assetStringPattern, (_match, _quote, assetPath) => {\n return `(window.skybridge?.serverUrl ?? \"\") + \"${assetPath}\"`;\n });\n\n return code;\n}\n\n/**\n * Vite plugin that transforms asset import paths to resolve at runtime via `window.skybridge.serverUrl`.\n */\nexport function assetBaseUrlTransformPlugin(): Plugin {\n return {\n name: \"asset-base-url-transform\",\n transform(code, id) {\n if (!code) {\n return null;\n }\n\n // Vite serves CSS modules as JS that embeds the stylesheet as a string\n // literal. Rewriting `url(\"/foo.woff2\")` inside that string to a JS\n // concatenation expression produces invalid CSS once it lands in a\n // <style> tag. CSS asset URLs are already handled at build time by\n // `experimental.renderBuiltUrl`, so skip CSS requests here.\n if (isCssRequest(id)) {\n return null;\n }\n\n const transformedCode = assetBaseUrlTransform(code);\n\n if (transformedCode === code) {\n return null;\n }\n\n return {\n code: transformedCode,\n map: null,\n };\n },\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { assetBaseUrlTransform } from "./asset-base-url-transform-plugin.js";
2
+ import { assetBaseUrlTransform, assetBaseUrlTransformPlugin, isCssRequest, } from "./asset-base-url-transform-plugin.js";
3
3
  describe("assetBaseUrlTransform", () => {
4
4
  it("should transform asset paths to use window.skybridge.serverUrl", () => {
5
5
  const cases = [
@@ -81,4 +81,54 @@ describe("assetBaseUrlTransform", () => {
81
81
  expect(result).toContain(`const logo = (window.skybridge?.serverUrl ?? "") + "/assets/logo.png";`);
82
82
  });
83
83
  });
84
+ describe("isCssRequest", () => {
85
+ it("returns true for CSS-family extensions", () => {
86
+ expect(isCssRequest("/src/styles.css")).toBe(true);
87
+ expect(isCssRequest("/src/styles.module.css")).toBe(true);
88
+ expect(isCssRequest("/src/styles.scss")).toBe(true);
89
+ expect(isCssRequest("/src/styles.sass")).toBe(true);
90
+ expect(isCssRequest("/src/styles.less")).toBe(true);
91
+ expect(isCssRequest("/src/styles.styl")).toBe(true);
92
+ });
93
+ it("returns true for CSS modules with Vite query strings", () => {
94
+ expect(isCssRequest("/src/styles.css?direct")).toBe(true);
95
+ expect(isCssRequest("/src/styles.css?inline")).toBe(true);
96
+ expect(isCssRequest("/src/styles.css?used")).toBe(true);
97
+ expect(isCssRequest("/src/Foo.vue?vue&type=style&lang.css")).toBe(true);
98
+ });
99
+ it("returns false for non-CSS modules", () => {
100
+ expect(isCssRequest("/src/index.tsx")).toBe(false);
101
+ expect(isCssRequest("/src/utils.ts")).toBe(false);
102
+ expect(isCssRequest("/src/Logo.svg")).toBe(false);
103
+ expect(isCssRequest("/src/notes.cssx")).toBe(false);
104
+ });
105
+ });
106
+ describe("assetBaseUrlTransformPlugin", () => {
107
+ function runTransform(id, code) {
108
+ const plugin = assetBaseUrlTransformPlugin();
109
+ const hook = plugin.transform;
110
+ if (!hook) {
111
+ throw new Error("plugin.transform is not defined");
112
+ }
113
+ const handler = typeof hook === "function" ? hook : hook.handler;
114
+ return handler.call(
115
+ // biome-ignore lint/suspicious/noExplicitAny: vitest harness for plugin hook
116
+ {}, code, id, { moduleType: "js" });
117
+ }
118
+ it("rewrites asset paths in JS modules", () => {
119
+ const result = runTransform("/src/widget.tsx", `const logo = "/assets/logo.png";`);
120
+ expect(result?.code).toContain(`(window.skybridge?.serverUrl ?? "") + "/assets/logo.png"`);
121
+ });
122
+ // Reproducer for #697: CSS imports are served as JS modules with the
123
+ // stylesheet embedded as a string. Rewriting url("/foo.woff2") inside that
124
+ // string would produce invalid CSS once the styles are injected.
125
+ it("does not rewrite asset paths when transforming a CSS module", () => {
126
+ const cssCode = `__vite__updateStyle("style-id", "@font-face { src: url(\\"/fonts/Brand.woff2\\") format(\\"woff2\\"); }");`;
127
+ expect(runTransform("/src/fonts.css", cssCode)).toBeNull();
128
+ expect(runTransform("/src/fonts.css?direct", cssCode)).toBeNull();
129
+ expect(runTransform("/src/fonts.css?inline", cssCode)).toBeNull();
130
+ expect(runTransform("/src/styles.scss", cssCode)).toBeNull();
131
+ expect(runTransform("/src/Foo.vue?vue&type=style&lang.css", cssCode)).toBeNull();
132
+ });
133
+ });
84
134
  //# sourceMappingURL=asset-base-url-transform-plugin.test.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"asset-base-url-transform-plugin.test.js","sourceRoot":"","sources":["../../src/server/asset-base-url-transform-plugin.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAE7E,QAAQ,CAAC,uBAAuB,EAAE,GAAG,EAAE;IACrC,EAAE,CAAC,gEAAgE,EAAE,GAAG,EAAE;QACxE,MAAM,KAAK,GAAG;YACZ;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,mCAAmC;gBACzC,QAAQ,EAAE,yEAAyE;aACpF;YACD;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,mCAAmC;gBACzC,QAAQ,EAAE,yEAAyE;aACpF;YACD;gBACE,IAAI,EAAE,iBAAiB;gBACvB,IAAI,EAAE,mCAAmC;gBACzC,QAAQ,EAAE,yEA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AC;IAEH,EAAE,CAAC,0EAA0E,EAAE,GAAG,EAAE;QAClF,2EAA2E;QAC3E,wEAAwE;QACxE,6DAA6D;QAC7D,8EAA8E;QAC9E,MAAM,KAAK,GAAG;YACZ,sEAAsE;YACtE,yCAAyC;YACzC,yCAAyC;YACzC,8CAA8C;YAC9C,sCAAsC;SACvC,CAAC;QAEF,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,MAAM,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjD,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,6FAA6F,EAAE,GAAG,EAAE;QACrG,MAAM,IAAI,GAAG;YACX,iCAAiC;YACjC,+CAA+C;YAC/C,kCAAkC;SACnC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,MAAM,MAAM,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;QAE3C,oBAAoB;QACpB,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAC;QAC5C,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC,2BAA2B,CAAC,CAAC;QACtD,2BAA2B;QAC3B,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,CACtB,wEAAwE,CACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, expect, it } from \"vitest\";\nimport { assetBaseUrlTransform } from \"./asset-base-url-transform-plugin.js\";\n\ndescribe(\"assetBaseUrlTransform\", () => {\n it(\"should transform asset paths to use window.skybridge.serverUrl\", () => {\n const cases = [\n {\n desc: \"single-quoted\",\n code: `const image = '/assets/logo.png';`,\n expected: `const image = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n },\n {\n desc: \"double-quoted\",\n code: `const image = \"/assets/logo.png\";`,\n expected: `const image = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n },\n {\n desc: \"backtick-quoted\",\n code: \"const image = `/assets/logo.png`;\",\n expected: `const image = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n },\n ];\n\n for (const { code, expected } of cases) {\n const result = assetBaseUrlTransform(code);\n expect(result).toBe(expected);\n }\n });\n\n it(\"should transform multiple asset paths\", () => {\n const code = `\n const logo = '/assets/logo.png';\n const icon = '/assets/icon.svg';\n const font = '/assets/font.woff2';\n `;\n const result = assetBaseUrlTransform(code);\n\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\"`,\n );\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/icon.svg\"`,\n );\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/font.woff2\"`,\n );\n });\n\n it(\"should not transform already absolute URLs\", () => {\n const code = `\n const local = '/assets/logo.png';\n const http = 'http://example.com/image.png';\n const https = 'https://example.com/image.png';\n `;\n const result = assetBaseUrlTransform(code);\n\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\"`,\n );\n expect(result).toContain(\"http://example.com/image.png\");\n expect(result).toContain(\"https://example.com/image.png\");\n });\n\n it(\"should not transform code without asset paths\", () => {\n const code = `const text = \"Hello World\";`;\n const result = assetBaseUrlTransform(code);\n\n expect(result).toBe(code);\n });\n\n it(\"should not transform asset paths inside static `import ... from` clauses\", () => {\n // Reproducer for #713: a dep does `import * as sprite from './icons.svg'`,\n // Vite resolves the relative path to absolute, then this transform used\n // to rewrite the resolved string — producing invalid JS like\n // `import * as sprite from (expr) + \"...\"` that crashes vite:import-analysis.\n const cases = [\n `import * as sprite from \"/Users/me/proj/node_modules/pkg/icons.svg\";`,\n `import sprite from '/assets/icons.svg';`,\n `import sprite from \"/assets/icons.svg\";`,\n `export { default } from \"/assets/icons.svg\";`,\n `export * from '/assets/sprites.svg';`,\n ];\n\n for (const code of cases) {\n expect(assetBaseUrlTransform(code)).toBe(code);\n }\n });\n\n it(\"should still transform value-position asset paths in files that also have unrelated imports\", () => {\n const code = [\n `import { foo } from \"./foo.js\";`,\n `import * as sprite from \"/assets/sprite.svg\";`,\n `const logo = \"/assets/logo.png\";`,\n ].join(\"\\n\");\n const result = assetBaseUrlTransform(code);\n\n // Imports untouched\n expect(result).toContain(`from \"./foo.js\"`);\n expect(result).toContain(`from \"/assets/sprite.svg\"`);\n // Value-position rewritten\n expect(result).toContain(\n `const logo = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n );\n });\n});\n"]}
1
+ {"version":3,"file":"asset-base-url-transform-plugin.test.js","sourceRoot":"","sources":["../../src/server/asset-base-url-transform-plugin.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAC3B,YAAY,GACb,MAAM,sCAAsC,CAAC;AAE9C,QAAQ,CAAC,uBAAuB,EAAE,GAAG,EAAE;IACrC,EAAE,CAAC,gEAAgE,EAAE,GAAG,EAAE;QACxE,MAAM,KAAK,GAAG;YACZ;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,mCAAmC;gBACzC,QAAQ,EAAE,yEAAyE;aACpF;YACD;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,mCAAmC;gBACzC,QAAQ,EAAE,yEAAyE;aACpF;YACD;gBACE,IAAI,EAAE,iBAAiB;gBACvB,IAAI,EAAE,mCAAmC;gBACzC,QAAQ,EAAE,yEAAyE;aACpF;SACF,CAAC;QAEF,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,KAAK,EAAE,CAAC;YACvC,MAAM,MAAM,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;YAC3C,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAChC,CAAC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UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;QACjE,OAAO,OAAO,CAAC,IAAI;QACjB,6EAA6E;QAC7E,EAAS,EACT,IAAI,EACJ,EAAE,EACF,EAAE,UAAU,EAAE,IAAI,EAAE,CACF,CAAC;IACvB,CAAC;IAED,EAAE,CAAC,oCAAoC,EAAE,GAAG,EAAE;QAC5C,MAAM,MAAM,GAAG,YAAY,CACzB,iBAAiB,EACjB,kCAAkC,CACnC,CAAC;QACF,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,SAAS,CAC5B,0DAA0D,CAC3D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,qEAAqE;IACrE,2EAA2E;IAC3E,iEAAiE;IACjE,EAAE,CAAC,6DAA6D,EAAE,GAAG,EAAE;QACrE,MAAM,OAAO,GAAG,4GAA4G,CAAC;QAE7H,MAAM,CAAC,YAAY,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC3D,MAAM,CAAC,YAAY,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QAClE,MAAM,CAAC,YAAY,CAAC,uBAAuB,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QAClE,MAAM,CAAC,YAAY,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC7D,MAAM,CACJ,YAAY,CAAC,sCAAsC,EAAE,OAAO,CAAC,CAC9D,CAAC,QAAQ,EAAE,CAAC;IACf,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, expect, it } from \"vitest\";\nimport {\n assetBaseUrlTransform,\n assetBaseUrlTransformPlugin,\n isCssRequest,\n} from \"./asset-base-url-transform-plugin.js\";\n\ndescribe(\"assetBaseUrlTransform\", () => {\n it(\"should transform asset paths to use window.skybridge.serverUrl\", () => {\n const cases = [\n {\n desc: \"single-quoted\",\n code: `const image = '/assets/logo.png';`,\n expected: `const image = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n },\n {\n desc: \"double-quoted\",\n code: `const image = \"/assets/logo.png\";`,\n expected: `const image = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n },\n {\n desc: \"backtick-quoted\",\n code: \"const image = `/assets/logo.png`;\",\n expected: `const image = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n },\n ];\n\n for (const { code, expected } of cases) {\n const result = assetBaseUrlTransform(code);\n expect(result).toBe(expected);\n }\n });\n\n it(\"should transform multiple asset paths\", () => {\n const code = `\n const logo = '/assets/logo.png';\n const icon = '/assets/icon.svg';\n const font = '/assets/font.woff2';\n `;\n const result = assetBaseUrlTransform(code);\n\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\"`,\n );\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/icon.svg\"`,\n );\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/font.woff2\"`,\n );\n });\n\n it(\"should not transform already absolute URLs\", () => {\n const code = `\n const local = '/assets/logo.png';\n const http = 'http://example.com/image.png';\n const https = 'https://example.com/image.png';\n `;\n const result = assetBaseUrlTransform(code);\n\n expect(result).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\"`,\n );\n expect(result).toContain(\"http://example.com/image.png\");\n expect(result).toContain(\"https://example.com/image.png\");\n });\n\n it(\"should not transform code without asset paths\", () => {\n const code = `const text = \"Hello World\";`;\n const result = assetBaseUrlTransform(code);\n\n expect(result).toBe(code);\n });\n\n it(\"should not transform asset paths inside static `import ... from` clauses\", () => {\n // Reproducer for #713: a dep does `import * as sprite from './icons.svg'`,\n // Vite resolves the relative path to absolute, then this transform used\n // to rewrite the resolved string — producing invalid JS like\n // `import * as sprite from (expr) + \"...\"` that crashes vite:import-analysis.\n const cases = [\n `import * as sprite from \"/Users/me/proj/node_modules/pkg/icons.svg\";`,\n `import sprite from '/assets/icons.svg';`,\n `import sprite from \"/assets/icons.svg\";`,\n `export { default } from \"/assets/icons.svg\";`,\n `export * from '/assets/sprites.svg';`,\n ];\n\n for (const code of cases) {\n expect(assetBaseUrlTransform(code)).toBe(code);\n }\n });\n\n it(\"should still transform value-position asset paths in files that also have unrelated imports\", () => {\n const code = [\n `import { foo } from \"./foo.js\";`,\n `import * as sprite from \"/assets/sprite.svg\";`,\n `const logo = \"/assets/logo.png\";`,\n ].join(\"\\n\");\n const result = assetBaseUrlTransform(code);\n\n // Imports untouched\n expect(result).toContain(`from \"./foo.js\"`);\n expect(result).toContain(`from \"/assets/sprite.svg\"`);\n // Value-position rewritten\n expect(result).toContain(\n `const logo = (window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\";`,\n );\n });\n});\n\ndescribe(\"isCssRequest\", () => {\n it(\"returns true for CSS-family extensions\", () => {\n expect(isCssRequest(\"/src/styles.css\")).toBe(true);\n expect(isCssRequest(\"/src/styles.module.css\")).toBe(true);\n expect(isCssRequest(\"/src/styles.scss\")).toBe(true);\n expect(isCssRequest(\"/src/styles.sass\")).toBe(true);\n expect(isCssRequest(\"/src/styles.less\")).toBe(true);\n expect(isCssRequest(\"/src/styles.styl\")).toBe(true);\n });\n\n it(\"returns true for CSS modules with Vite query strings\", () => {\n expect(isCssRequest(\"/src/styles.css?direct\")).toBe(true);\n expect(isCssRequest(\"/src/styles.css?inline\")).toBe(true);\n expect(isCssRequest(\"/src/styles.css?used\")).toBe(true);\n expect(isCssRequest(\"/src/Foo.vue?vue&type=style&lang.css\")).toBe(true);\n });\n\n it(\"returns false for non-CSS modules\", () => {\n expect(isCssRequest(\"/src/index.tsx\")).toBe(false);\n expect(isCssRequest(\"/src/utils.ts\")).toBe(false);\n expect(isCssRequest(\"/src/Logo.svg\")).toBe(false);\n expect(isCssRequest(\"/src/notes.cssx\")).toBe(false);\n });\n});\n\ndescribe(\"assetBaseUrlTransformPlugin\", () => {\n type TransformResult = { code: string; map: null } | null;\n\n function runTransform(id: string, code: string): TransformResult {\n const plugin = assetBaseUrlTransformPlugin();\n const hook = plugin.transform;\n if (!hook) {\n throw new Error(\"plugin.transform is not defined\");\n }\n const handler = typeof hook === \"function\" ? hook : hook.handler;\n return handler.call(\n // biome-ignore lint/suspicious/noExplicitAny: vitest harness for plugin hook\n {} as any,\n code,\n id,\n { moduleType: \"js\" },\n ) as TransformResult;\n }\n\n it(\"rewrites asset paths in JS modules\", () => {\n const result = runTransform(\n \"/src/widget.tsx\",\n `const logo = \"/assets/logo.png\";`,\n );\n expect(result?.code).toContain(\n `(window.skybridge?.serverUrl ?? \"\") + \"/assets/logo.png\"`,\n );\n });\n\n // Reproducer for #697: CSS imports are served as JS modules with the\n // stylesheet embedded as a string. Rewriting url(\"/foo.woff2\") inside that\n // string would produce invalid CSS once the styles are injected.\n it(\"does not rewrite asset paths when transforming a CSS module\", () => {\n const cssCode = `__vite__updateStyle(\"style-id\", \"@font-face { src: url(\\\\\"/fonts/Brand.woff2\\\\\") format(\\\\\"woff2\\\\\"); }\");`;\n\n expect(runTransform(\"/src/fonts.css\", cssCode)).toBeNull();\n expect(runTransform(\"/src/fonts.css?direct\", cssCode)).toBeNull();\n expect(runTransform(\"/src/fonts.css?inline\", cssCode)).toBeNull();\n expect(runTransform(\"/src/styles.scss\", cssCode)).toBeNull();\n expect(\n runTransform(\"/src/Foo.vue?vue&type=style&lang.css\", cssCode),\n ).toBeNull();\n });\n});\n"]}
@@ -0,0 +1,8 @@
1
+ import { z } from "zod";
2
+ export declare const FileRef: z.ZodObject<{
3
+ file_id: z.ZodString;
4
+ download_url: z.ZodString;
5
+ mime_type: z.ZodOptional<z.ZodString>;
6
+ file_name: z.ZodOptional<z.ZodString>;
7
+ }, z.core.$strip>;
8
+ export type FileRef = z.infer<typeof FileRef>;
@@ -0,0 +1,8 @@
1
+ import { z } from "zod";
2
+ export const FileRef = z.object({
3
+ file_id: z.string(),
4
+ download_url: z.string(),
5
+ mime_type: z.string().optional(),
6
+ file_name: z.string().optional(),
7
+ });
8
+ //# sourceMappingURL=file-ref.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-ref.js","sourceRoot":"","sources":["../../src/server/file-ref.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE;IACnB,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE;IACxB,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAChC,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACjC,CAAC,CAAC","sourcesContent":["import { z } from \"zod\";\n\nexport const FileRef = z.object({\n file_id: z.string(),\n download_url: z.string(),\n mime_type: z.string().optional(),\n file_name: z.string().optional(),\n});\n\nexport type FileRef = z.infer<typeof FileRef>;\n"]}
@@ -1,4 +1,5 @@
1
1
  export { audio, embeddedResource, image, resourceLink, text, } from "./content-helpers.js";
2
+ export { FileRef } from "./file-ref.js";
2
3
  export type { AnyToolRegistry, InferTools, ToolInput, ToolNames, ToolOutput, ToolResponseMetadata, } from "./inferUtilityTypes.js";
3
4
  export type { McpExtra, McpMethodString, McpMiddlewareFilter, McpMiddlewareFn, McpResultFor, McpTypedMiddlewareFn, McpWildcard, } from "./middleware.js";
4
5
  export type { HandlerContent, KnownToolMeta, McpServerTypes, ToolDef, ToolMeta, ViewConfig, ViewCsp, ViewHostType, ViewName, ViewNameRegistry, } from "./server.js";
@@ -1,4 +1,5 @@
1
1
  export { audio, embeddedResource, image, resourceLink, text, } from "./content-helpers.js";
2
+ export { FileRef } from "./file-ref.js";
2
3
  export { McpServer, normalizeContent, } from "./server.js";
3
4
  export { viewsDevServer } from "./viewsDevServer.js";
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,IAAI,GACL,MAAM,sBAAsB,CAAC;AA8B9B,OAAO,EACL,SAAS,EACT,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n audio,\n embeddedResource,\n image,\n resourceLink,\n text,\n} from \"./content-helpers.js\";\nexport type {\n AnyToolRegistry,\n InferTools,\n ToolInput,\n ToolNames,\n ToolOutput,\n ToolResponseMetadata,\n} from \"./inferUtilityTypes.js\";\nexport type {\n McpExtra,\n McpMethodString,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nexport type {\n HandlerContent,\n KnownToolMeta,\n McpServerTypes,\n ToolDef,\n ToolMeta,\n ViewConfig,\n ViewCsp,\n ViewHostType,\n ViewName,\n ViewNameRegistry,\n} from \"./server.js\";\nexport {\n McpServer,\n normalizeContent,\n} from \"./server.js\";\nexport { viewsDevServer } from \"./viewsDevServer.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,IAAI,GACL,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AA8BxC,OAAO,EACL,SAAS,EACT,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n audio,\n embeddedResource,\n image,\n resourceLink,\n text,\n} from \"./content-helpers.js\";\nexport { FileRef } from \"./file-ref.js\";\nexport type {\n AnyToolRegistry,\n InferTools,\n ToolInput,\n ToolNames,\n ToolOutput,\n ToolResponseMetadata,\n} from \"./inferUtilityTypes.js\";\nexport type {\n McpExtra,\n McpMethodString,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nexport type {\n HandlerContent,\n KnownToolMeta,\n McpServerTypes,\n ToolDef,\n ToolMeta,\n ViewConfig,\n ViewCsp,\n ViewHostType,\n ViewName,\n ViewNameRegistry,\n} from \"./server.js\";\nexport {\n McpServer,\n normalizeContent,\n} from \"./server.js\";\nexport { viewsDevServer } from \"./viewsDevServer.js\";\n"]}
@@ -1,8 +1,9 @@
1
+ import type { McpUiToolMeta } from "@modelcontextprotocol/ext-apps";
1
2
  import { type ServerOptions } from "@modelcontextprotocol/sdk/server/index.js";
2
3
  import { McpServer as McpServerBase } from "@modelcontextprotocol/sdk/server/mcp.js";
3
4
  import type { AnySchema, SchemaOutput, ZodRawShapeCompat } from "@modelcontextprotocol/sdk/server/zod-compat.js";
4
5
  import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
5
- import type { ContentBlock, Implementation, ServerNotification, ServerRequest, ServerResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
6
+ import type { ContentBlock, Implementation, RequestMeta, ServerNotification, ServerRequest, ServerResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
6
7
  import { type ErrorRequestHandler, type Express, type RequestHandler } from "express";
7
8
  import type { McpExtra, McpExtraFor, McpMethodString, McpMiddlewareFilter, McpMiddlewareFn, McpResultFor, McpTypedMiddlewareFn, McpWildcard } from "./middleware.js";
8
9
  export type ToolDef<TInput = unknown, TOutput = unknown, TResponseMetadata = unknown> = {
@@ -39,6 +40,8 @@ export interface KnownToolMeta {
39
40
  "openai/widgetAccessible"?: boolean;
40
41
  "openai/toolInvocation/invoking"?: string;
41
42
  "openai/toolInvocation/invoked"?: string;
43
+ "openai/fileParams"?: string[];
44
+ ui?: Pick<McpUiToolMeta, "visibility">;
42
45
  }
43
46
  export type ToolMeta = KnownToolMeta & Record<string, unknown>;
44
47
  export type HandlerContent = string | ContentBlock | ContentBlock[];
@@ -86,11 +89,43 @@ interface ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> {
86
89
  view?: ViewConfig;
87
90
  _meta?: ToolMeta;
88
91
  }
92
+ /**
93
+ * Optional client-supplied hints attached to `params._meta` on every tool call
94
+ * by the Apps SDK host. Hints only: never use for authorization, and tolerate
95
+ * absence.
96
+ * @see https://developers.openai.com/apps-sdk/reference#_meta-fields-the-client-provides
97
+ */
98
+ export interface ClientHintsMeta {
99
+ /** Requested locale (BCP-47, e.g. `"en-US"`). */
100
+ "openai/locale"?: string;
101
+ /** Browser user-agent */
102
+ "openai/userAgent"?: string;
103
+ /** Coarse user location. May be partially populated. */
104
+ "openai/userLocation"?: {
105
+ city?: string;
106
+ region?: string;
107
+ country?: string;
108
+ timezone?: string;
109
+ longitude?: number;
110
+ latitude?: number;
111
+ };
112
+ /** Anonymized user id. */
113
+ "openai/subject"?: string;
114
+ /** Anonymized conversation id, stable within a ChatGPT session. */
115
+ "openai/session"?: string;
116
+ /** Anonymized organization id, when the user account is part of an organization. */
117
+ "openai/organization"?: string;
118
+ /** Stable id for the currently mounted widget instance. */
119
+ "openai/widgetSessionId"?: string;
120
+ }
121
+ type ToolHandlerExtra = Omit<RequestHandlerExtra<ServerRequest, ServerNotification>, "_meta"> & {
122
+ _meta?: RequestMeta & ClientHintsMeta;
123
+ };
89
124
  type ToolHandler<TInput extends ZodRawShapeCompat, TReturn extends {
90
125
  content?: HandlerContent;
91
126
  } = {
92
127
  content?: HandlerContent;
93
- }> = (args: ShapeOutput<TInput>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => TReturn | Promise<TReturn>;
128
+ }> = (args: ShapeOutput<TInput>, extra: ToolHandlerExtra) => TReturn | Promise<TReturn>;
94
129
  export declare function normalizeContent(content: HandlerContent | undefined): ContentBlock[];
95
130
  interface McpServerBaseOmitted extends Omit<McpServerBase, "registerTool" | "connect"> {
96
131
  }
@@ -303,7 +303,7 @@ export class McpServer extends McpServerBaseOmitted {
303
303
  });
304
304
  // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs
305
305
  toolMeta["ui/resourceUri"] = viewResource.uri;
306
- toolMeta.ui = { resourceUri: viewResource.uri };
306
+ toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };
307
307
  }
308
308
  }
309
309
  registerViewResource({ name, viewResource, view, }) {
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAK7B,OAAO,EACL,MAAM,IAAI,SAAS,GAEpB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,SAAS,IAAI,aAAa,EAAE,MAAM,yCAAyC,CAAC;AAerF,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,OAAO,EAAE,EAIf,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAYpD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,MAAM,cAAc,GAAG,CACrB,MAAS,EACT,MAAS,EACF,EAAE;IACT,OAAO,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE;QACxD,IAAI,KAAK,CAAC,OAAO,CAAC,SAA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AAC,CAAmC,CAAC;QAErD,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,UAAU,EAAE,GAAG,MAAM,CAAC;QAElE,MAAM,QAAQ,GAAqB,EAAE,GAAG,YAAY,EAAE,CAAC;QAEvD,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YACjD,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QACnD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE1E,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC;QAEvE,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n Server as SdkServer,\n type ServerOptions,\n} from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { McpServer as McpServerBase } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n AnySchema,\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ContentBlock,\n Implementation,\n ServerNotification,\n ServerRequest,\n ServerResult,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport { createApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type {\n McpExtra,\n McpExtraFor,\n McpMethodString,\n McpMiddlewareEntry,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport { templateHelper } from \"./templateHelper.js\";\n\nconst mergeWithUnion = <T extends object, S extends object>(\n target: T,\n source: S,\n): T & S => {\n return mergeWith(target, source, (targetVal, sourceVal) => {\n if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n return union(targetVal, sourceVal);\n }\n });\n};\n\nexport type ToolDef<\n TInput = unknown,\n TOutput = unknown,\n TResponseMetadata = unknown,\n> = {\n input: TInput;\n output: TOutput;\n responseMetadata: TResponseMetadata;\n};\n\nexport type ViewHostType = \"apps-sdk\" | \"mcp-app\";\n\nexport interface ViewCsp {\n /** Origins for static assets (images, fonts, scripts, styles). */\n resourceDomains?: string[];\n /** Origins the view may contact via fetch/XHR. */\n connectDomains?: string[];\n /** Origins allowed for iframe embeds (opts into stricter app review). */\n frameDomains?: string[];\n /** Origins that can receive openExternal redirects without the safe-link modal. */\n redirectDomains?: string[];\n /** Origins allowed in `<base href>` tags (mcp-apps only). */\n baseUriDomains?: string[];\n}\n\n// Must be exported: TS module augmentation only merges with exported\n// declarations. Without `export`, `.skybridge/views.d.ts` augmentation\n// would create a separate interface and `ViewName` would stay `string`.\n// biome-ignore lint/suspicious/noEmptyInterface: register pattern — augmented by `.skybridge/views.d.ts` to narrow ViewName\nexport interface ViewNameRegistry {}\n\nexport type ViewName = keyof ViewNameRegistry & string;\n\nexport interface ViewConfig {\n component: ViewName;\n description?: string;\n hosts?: ViewHostType[];\n prefersBorder?: boolean;\n domain?: string;\n csp?: ViewCsp;\n _meta?: Record<string, unknown>;\n}\n\nexport interface KnownToolMeta {\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n}\n\nexport type ToolMeta = KnownToolMeta & Record<string, unknown>;\n\nexport type HandlerContent = string | ContentBlock | ContentBlock[];\n\n/** @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters */\ntype ViteManifestEntry = {\n file: string;\n name?: string;\n src?: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n css?: string[];\n assets?: string[];\n imports?: string[];\n dynamicImports?: string[];\n};\n\ntype OpenaiToolMeta = {\n \"openai/outputTemplate\": string;\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n};\n\n/** @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#resource-discovery */\ntype McpAppsToolMeta = {\n ui: McpUiToolMeta;\n};\n\ntype InternalToolMeta = Partial<OpenaiToolMeta & McpAppsToolMeta>;\n\n/** @see https://developers.openai.com/apps-sdk/reference#component-resource-_meta-fields */\ntype OpenaiViewCSP = {\n connect_domains: string[];\n resource_domains: string[];\n frame_domains?: string[];\n redirect_domains?: string[];\n};\n\ntype OpenaiResourceMeta = {\n \"openai/widgetDescription\"?: string;\n \"openai/widgetPrefersBorder\"?: boolean;\n \"openai/widgetCSP\"?: OpenaiViewCSP;\n \"openai/widgetDomain\"?: string;\n};\n\n/**\n * MCP Apps CSP extended with upcoming / Skybridge-specific fields.\n * @see https://github.com/modelcontextprotocol/ext-apps/pull/158\n */\ntype ExtendedMcpUiResourceCsp = McpUiResourceMeta[\"csp\"] & {\n /**\n * Origins that can receive openExternal redirects without the safe-link modal.\n * OpenAI-specific; mirrored into the mcp-apps CSP for cross-host parity.\n * @see https://developers.openai.com/apps-sdk/reference#component-resource-_meta-fields\n */\n redirectDomains?: string[];\n};\n\ntype ExtendedMcpUiResourceMeta = Omit<McpUiResourceMeta, \"csp\"> & {\n csp?: ExtendedMcpUiResourceCsp;\n};\n\ntype McpAppsResourceMeta = {\n ui?: ExtendedMcpUiResourceMeta;\n};\n\ntype ResourceMeta = OpenaiResourceMeta | McpAppsResourceMeta;\n\ntype ViewResourceConfig<T extends ResourceMeta = ResourceMeta> = {\n hostType: ViewHostType;\n uri: string;\n mimeType: string;\n buildContentMeta: (\n defaults: {\n resourceDomains: string[];\n connectDomains: string[];\n domain: string;\n baseUriDomains: string[];\n },\n overrides: { domain?: string },\n ) => T;\n};\n\n/**\n * Type-level marker interface for cross-package type inference.\n *\n * Consumers infer tool types via the structural `$types` property rather than\n * the `McpServer` class generic, because class-generic inference breaks when\n * `McpServer` comes from different package installations (e.g. a consumer\n * with its own `skybridge` dep vs. the in-tree workspace version).\n *\n * Inspired by tRPC's `_def` pattern and Hono's type markers.\n */\nexport interface McpServerTypes<TTools extends Record<string, ToolDef>> {\n readonly tools: TTools;\n}\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype ShapeOutput<Shape extends ZodRawShapeCompat> = Simplify<\n {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n }\n>;\n\ntype ExtractStructuredContent<T> = T extends { structuredContent: infer SC }\n ? Simplify<SC>\n : never;\n\ntype ExtractMeta<T> = [Extract<T, { _meta: unknown }>] extends [never]\n ? unknown\n : Extract<T, { _meta: unknown }> extends { _meta: infer M }\n ? Simplify<M>\n : unknown;\n\ntype AddTool<\n TTools,\n TName extends string,\n TInput extends ZodRawShapeCompat,\n TOutput,\n TResponseMetadata = unknown,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n }\n>;\n\ninterface ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: ZodRawShapeCompat | AnySchema;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n _meta?: ToolMeta;\n}\n\ntype ToolHandler<\n TInput extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent } = { content?: HandlerContent },\n> = (\n args: ShapeOutput<TInput>,\n extra: RequestHandlerExtra<ServerRequest, ServerNotification>,\n) => TReturn | Promise<TReturn>;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\nexport function normalizeContent(\n content: HandlerContent | undefined,\n): ContentBlock[] {\n if (content === undefined) {\n return [];\n }\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n if (Array.isArray(content)) {\n return content;\n }\n return [content];\n}\n\n// We Omit `registerTool` from the base class at the type level so our\n// unified 2-arg signature can replace the SDK's 3-arg one without an\n// incompatible override. The runtime prototype chain is unaffected.\ninterface McpServerBaseOmitted\n extends Omit<McpServerBase, \"registerTool\" | \"connect\"> {}\nconst McpServerBaseOmitted = McpServerBase as unknown as new (\n ...args: ConstructorParameters<typeof McpServerBase>\n) => McpServerBaseOmitted;\n\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `server.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied. Register your handlers before `run()`;\n * after `run()`, dev-mode middleware, the `/mcp` route, and the default\n * error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n readonly express: Express;\n private customErrorMiddleware: ErrorMiddlewareConfig[] = [];\n private mcpMiddlewareEntries: McpMiddlewareEntry[] = [];\n private mcpMiddlewareApplied = false;\n private claimedViews = new Map<string, string>();\n private viteManifest: Record<string, ViteManifestEntry> | null = null;\n private readonly serverInfo: Implementation;\n private readonly serverOptions?: ServerOptions;\n\n constructor(serverInfo: Implementation, options?: ServerOptions) {\n super(serverInfo, options);\n this.serverInfo = serverInfo;\n this.serverOptions = options;\n this.express = express();\n this.express.use(express.json());\n }\n\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.express.use(pathOrHandler, ...handlers);\n } else {\n this.express.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.customErrorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.customErrorMiddleware.push({\n handlers: [pathOrHandler, ...handlers],\n });\n }\n return this;\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn): this;\n /** Register MCP protocol-level middleware for all requests (`extra` is `McpExtra`). */\n mcpMiddleware(\n filter: \"request\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtra,\n next: () => Promise<ServerResult>,\n ) => Promise<unknown> | unknown,\n ): this;\n /** Register MCP protocol-level middleware for all notifications (`extra` is `undefined`). */\n mcpMiddleware(\n filter: \"notification\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: undefined,\n next: () => Promise<undefined>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware for an exact method.\n * Narrows `params`, `extra`, and `next()` result based on the method string.\n */\n mcpMiddleware<M extends McpMethodString>(\n filter: M,\n handler: McpTypedMiddlewareFn<M>,\n ): this;\n /**\n * Register MCP protocol-level middleware for a wildcard pattern (e.g. `\"tools/*\"`).\n * `next()` returns the union of result types for matching methods.\n */\n mcpMiddleware<W extends McpWildcard>(\n filter: W,\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtraFor<W>,\n next: () => Promise<McpResultFor<W>>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware with a method filter.\n * Filter can be an exact method (`\"tools/call\"`), wildcard (`\"tools/*\"`),\n * category (`\"request\"` | `\"notification\"`), or an array of those.\n */\n mcpMiddleware(filter: McpMiddlewareFilter, handler: McpMiddlewareFn): this;\n mcpMiddleware(\n filterOrHandler: McpMiddlewareFilter | McpMiddlewareFn,\n // biome-ignore lint/suspicious/noExplicitAny: overloads narrow the handler type at call sites; implementation must accept all variants\n maybeHandler?: any,\n ): this {\n if (this.mcpMiddlewareApplied) {\n throw new Error(\n \"Cannot register MCP middleware after run() or connect() has been called\",\n );\n }\n\n const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.mcpMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler,\n });\n } else if (handler) {\n this.mcpMiddlewareEntries.push({\n filter: filterOrHandler,\n handler,\n });\n } else {\n throw new Error(\n \"mcpMiddleware requires a handler function when a filter is provided\",\n );\n }\n\n return this;\n }\n\n private applyMcpMiddleware(): void {\n if (this.mcpMiddlewareApplied) {\n return;\n }\n this.mcpMiddlewareApplied = true;\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = monitoringEntry\n ? [monitoringEntry, ...this.mcpMiddlewareEntries]\n : this.mcpMiddlewareEntries;\n\n if (entries.length === 0) {\n return;\n }\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n\n async connect(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n return McpServerBase.prototype.connect.call(this, transport);\n }\n\n /**\n * Per-request stateless connect. The SDK's `Protocol` only allows one\n * transport per instance, so we can't reuse this `McpServer` across\n * concurrent requests. The SDK's idiomatic fix is a `() => McpServer`\n * factory, but that would break Skybridge's singleton API — so instead\n * we build a fresh underlying `Server` per request and share the main\n * server's handler maps by reference. The cast is unavoidable: there's\n * no public API to inject handler maps. `getHandlerMaps` validates the\n * read side and fails fast on SDK field renames.\n */\n async connectStatelessTransport(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n const fresh = new SdkServer(this.serverInfo, this.serverOptions);\n const target = fresh as unknown as {\n _requestHandlers: unknown;\n _notificationHandlers: unknown;\n };\n target._requestHandlers = requestHandlers;\n target._notificationHandlers = notificationHandlers;\n\n await fresh.connect(transport);\n }\n\n async run(): Promise<{ fetch: (...args: unknown[]) => unknown } | undefined> {\n this.applyMcpMiddleware();\n const httpServer = http.createServer();\n\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n\n httpServer.on(\"request\", this.express);\n const port = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(port, () => {\n resolve();\n });\n });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private enforceOneToolPerView(component: string, toolName: string): void {\n const existingTool = this.claimedViews.get(component);\n if (existingTool) {\n throw new Error(\n `skybridge: view \"${component}\" is already used by tool \"${existingTool}\". Tool \"${toolName}\" cannot also reference it — each view backs exactly one tool.`,\n );\n }\n this.claimedViews.set(component, toolName);\n }\n\n private registerViewResources(\n toolName: string,\n view: ViewConfig,\n toolMeta: InternalToolMeta,\n ): void {\n const hosts = view.hosts ?? ([\"apps-sdk\", \"mcp-app\"] as const);\n\n // Append a content-derived version param so hosts (e.g. ChatGPT) bust\n // their cache when the bundle changes, but keep the URI stable across\n // `tools/list` calls when the bundle hasn't changed.\n const versionParam = this.computeViewVersionParam(view.component);\n\n if (hosts.includes(\"apps-sdk\")) {\n const viewResource: ViewResourceConfig<OpenaiResourceMeta> = {\n hostType: \"apps-sdk\",\n uri: `ui://views/apps-sdk/${view.component}.html${versionParam}`,\n mimeType: \"text/html+skybridge\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain },\n overrides,\n ) => {\n const defaults: OpenaiResourceMeta = {\n \"openai/widgetCSP\": {\n resource_domains: resourceDomains,\n connect_domains: connectDomains,\n },\n \"openai/widgetDomain\": domain,\n \"openai/widgetDescription\": view.description,\n };\n\n const fromView: Partial<\n Omit<\n OpenaiResourceMeta,\n \"openai/widgetCSP\" | \"openai/widgetDescription\"\n > & {\n \"openai/widgetCSP\": Partial<OpenaiViewCSP>;\n }\n > = {\n \"openai/widgetCSP\": {\n resource_domains: view.csp?.resourceDomains,\n connect_domains: view.csp?.connectDomains,\n frame_domains: view.csp?.frameDomains,\n redirect_domains: view.csp?.redirectDomains,\n },\n \"openai/widgetDomain\": view.domain,\n \"openai/widgetPrefersBorder\": view.prefersBorder,\n };\n\n const base = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n \"openai/widgetDomain\": overrides.domain,\n });\n\n if (view._meta) {\n return { ...base, ...view._meta } as OpenaiResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({\n name: toolName,\n viewResource,\n view,\n });\n toolMeta[\"openai/outputTemplate\"] = viewResource.uri;\n }\n\n if (hosts.includes(\"mcp-app\")) {\n const viewResource: ViewResourceConfig<McpAppsResourceMeta> = {\n hostType: \"mcp-app\",\n uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,\n mimeType: \"text/html;profile=mcp-app\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain, baseUriDomains },\n overrides,\n ) => {\n const defaults: McpAppsResourceMeta = {\n ui: {\n csp: {\n resourceDomains,\n connectDomains,\n baseUriDomains,\n },\n domain,\n },\n };\n\n const fromView: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n ...(view.domain && { domain: view.domain }),\n csp: {\n ...(view.csp?.resourceDomains && {\n resourceDomains: view.csp.resourceDomains,\n }),\n ...(view.csp?.connectDomains && {\n connectDomains: view.csp.connectDomains,\n }),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n ...(view.csp?.baseUriDomains && {\n baseUriDomains: view.csp.baseUriDomains,\n }),\n ...(view.csp?.redirectDomains && {\n redirectDomains: view.csp.redirectDomains,\n }),\n },\n },\n };\n\n const base = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n ui: overrides,\n });\n\n if (view._meta) {\n return { ...base, ...view._meta } as McpAppsResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({\n name: toolName,\n viewResource,\n view,\n });\n // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs\n toolMeta[\"ui/resourceUri\"] = viewResource.uri;\n toolMeta.ui = { resourceUri: viewResource.uri };\n }\n }\n\n private registerViewResource({\n name,\n viewResource,\n view,\n }: {\n name: string;\n viewResource: ViewResourceConfig;\n view: ViewConfig;\n }): void {\n const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;\n\n this.registerResource(\n name,\n viewUri,\n { description: view.description },\n async (uri, extra) => {\n const isProduction = process.env.NODE_ENV === \"production\";\n const isClaude =\n extra?.requestInfo?.headers?.[\"user-agent\"] === \"Claude-User\";\n\n const headers = extra?.requestInfo?.headers || {};\n const header = (key: string) => {\n const val = headers[key];\n return Array.isArray(val) ? val[0] : val;\n };\n\n let serverUrl: string;\n\n const forwardedHost = header(\"x-forwarded-host\");\n const origin = header(\"origin\");\n const host = header(\"host\");\n\n if (forwardedHost) {\n const proto = header(\"x-forwarded-proto\") || \"https\";\n serverUrl = `${proto}://${forwardedHost}`;\n } else if (origin) {\n serverUrl = origin;\n } else if (host) {\n const proto = [\"127.0.0.1:\", \"localhost:\"].some((p) =>\n host.startsWith(p),\n )\n ? \"http\"\n : \"https\";\n serverUrl = `${proto}://${host}`;\n } else {\n const devPort = process.env.__PORT || \"3000\";\n serverUrl = `http://localhost:${devPort}`;\n }\n\n const html = isProduction\n ? templateHelper.renderProduction({\n hostType,\n serverUrl,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\n hostType,\n serverUrl,\n viewName: view.component,\n });\n\n const connectDomains = [serverUrl];\n if (!isProduction) {\n const wsUrl = new URL(serverUrl);\n wsUrl.protocol = wsUrl.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n connectDomains.push(wsUrl.origin);\n }\n\n let contentMetaOverrides: { domain?: string } = {};\n if (isClaude) {\n const pathname = extra?.requestInfo?.url?.pathname ?? \"\";\n const rawUrl =\n header(\"x-alpic-forwarded-url\") ?? `${serverUrl}${pathname}`;\n // Strip a lone trailing slash so the hash matches the connector URL\n // as registered with Claude (which has no trailing slash on bare origins).\n const url = rawUrl.endsWith(\"/\") ? rawUrl.slice(0, -1) : rawUrl;\n const hash = crypto\n .createHash(\"sha256\")\n .update(url)\n .digest(\"hex\")\n .slice(0, 32);\n contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };\n }\n\n const contentMeta = buildContentMeta(\n {\n resourceDomains: [serverUrl],\n connectDomains,\n domain: serverUrl,\n baseUriDomains: [serverUrl],\n },\n contentMetaOverrides,\n );\n\n return {\n contents: [\n { uri: uri.href, mimeType, text: html, _meta: contentMeta },\n ],\n };\n },\n );\n }\n\n private wrapHandler<InputArgs extends ZodRawShapeCompat>(\n cb: ToolHandler<InputArgs>,\n { attachViewUUID }: { attachViewUUID: boolean },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n const result = await cb(args, extra);\n return {\n ...result,\n content: normalizeContent(result.content),\n ...(attachViewUUID && {\n _meta: {\n ...(result as { _meta?: Record<string, unknown> })._meta,\n viewUUID: crypto.randomUUID(),\n },\n }),\n };\n };\n }\n\n private computeViewVersionParam(viewName: string): string {\n if (process.env.NODE_ENV !== \"production\") {\n return \"\";\n }\n try {\n const viewFile = this.lookupViewFile(viewName);\n const styleFile = this.lookupDistFile(\"style.css\") ?? \"\";\n const hash = crypto\n .createHash(\"sha256\")\n .update(viewFile)\n .update(\"\\0\")\n .update(styleFile)\n .digest(\"hex\")\n .slice(0, 8);\n return `?v=${hash}`;\n } catch {\n return \"\";\n }\n }\n\n private lookupViewFile(viewName: string) {\n const manifest = this.readManifest();\n for (const entry of Object.values(manifest)) {\n if (entry?.isEntry && entry.name === viewName && entry.file) {\n return entry.file;\n }\n }\n throw new Error(\n `View \"${viewName}\" not found in Vite manifest. Did the build complete successfully? Look for an entry with name \"${viewName}\" in dist/assets/.vite/manifest.json.`,\n );\n }\n\n private lookupDistFile(key: string) {\n const manifest = this.readManifest();\n return manifest[key]?.file;\n }\n\n /**\n * Inject the Vite manifest as a value rather than letting `readManifest()`\n * load it from disk. Required for runtimes without a usable filesystem\n * (Cloudflare Workers, etc.) — the user's `skybridge build` emits the\n * manifest as a JS module which the entry imports and passes here.\n */\n setViteManifest(manifest: Record<string, { file: string }>): this {\n this.viteManifest = manifest as Record<string, ViteManifestEntry>;\n return this;\n }\n\n private readManifest(): Record<string, ViteManifestEntry> {\n if (this.viteManifest) {\n return this.viteManifest;\n }\n return JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n }\n\n registerTool<\n TName extends string,\n InputArgs extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>\n >;\n registerTool<InputArgs extends ZodRawShapeCompat>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs>,\n ): this;\n registerTool(...args: unknown[]): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n if (typeof args[0] === \"string\") {\n baseFn.call(this, args[0], args[1], args[2]);\n return this;\n }\n\n const config = args[0] as ToolConfig<ZodRawShapeCompat>;\n const cb = args[1] as ToolHandler<ZodRawShapeCompat>;\n\n const { name, view, _meta: userToolMeta, ...toolFields } = config;\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n if (view) {\n this.enforceOneToolPerView(view.component, name);\n this.registerViewResources(name, view, toolMeta);\n }\n\n const wrappedCb = this.wrapHandler(cb, { attachViewUUID: Boolean(view) });\n\n baseFn.call(this, name, { ...toolFields, _meta: toolMeta }, wrappedCb);\n\n return this;\n }\n}\n"]}
1
+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AC,CAAC;QACnD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE1E,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC;QAEvE,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n Server as SdkServer,\n type ServerOptions,\n} from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { McpServer as McpServerBase } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n AnySchema,\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ContentBlock,\n Implementation,\n RequestMeta,\n ServerNotification,\n ServerRequest,\n ServerResult,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport { createApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type {\n McpExtra,\n McpExtraFor,\n McpMethodString,\n McpMiddlewareEntry,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport { templateHelper } from \"./templateHelper.js\";\n\nconst mergeWithUnion = <T extends object, S extends object>(\n target: T,\n source: S,\n): T & S => {\n return mergeWith(target, source, (targetVal, sourceVal) => {\n if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n return union(targetVal, sourceVal);\n }\n });\n};\n\nexport type ToolDef<\n TInput = unknown,\n TOutput = unknown,\n TResponseMetadata = unknown,\n> = {\n input: TInput;\n output: TOutput;\n responseMetadata: TResponseMetadata;\n};\n\nexport type ViewHostType = \"apps-sdk\" | \"mcp-app\";\n\nexport interface ViewCsp {\n /** Origins for static assets (images, fonts, scripts, styles). */\n resourceDomains?: string[];\n /** Origins the view may contact via fetch/XHR. */\n connectDomains?: string[];\n /** Origins allowed for iframe embeds (opts into stricter app review). */\n frameDomains?: string[];\n /** Origins that can receive openExternal redirects without the safe-link modal. */\n redirectDomains?: string[];\n /** Origins allowed in `<base href>` tags (mcp-apps only). */\n baseUriDomains?: string[];\n}\n\n// Must be exported: TS module augmentation only merges with exported\n// declarations. Without `export`, `.skybridge/views.d.ts` augmentation\n// would create a separate interface and `ViewName` would stay `string`.\n// biome-ignore lint/suspicious/noEmptyInterface: register pattern — augmented by `.skybridge/views.d.ts` to narrow ViewName\nexport interface ViewNameRegistry {}\n\nexport type ViewName = keyof ViewNameRegistry & string;\n\nexport interface ViewConfig {\n component: ViewName;\n description?: string;\n hosts?: ViewHostType[];\n prefersBorder?: boolean;\n domain?: string;\n csp?: ViewCsp;\n _meta?: Record<string, unknown>;\n}\n\nexport interface KnownToolMeta {\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n \"openai/fileParams\"?: string[];\n ui?: Pick<McpUiToolMeta, \"visibility\">;\n}\n\nexport type ToolMeta = KnownToolMeta & Record<string, unknown>;\n\nexport type HandlerContent = string | ContentBlock | ContentBlock[];\n\n/** @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters */\ntype ViteManifestEntry = {\n file: string;\n name?: string;\n src?: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n css?: string[];\n assets?: string[];\n imports?: string[];\n dynamicImports?: string[];\n};\n\ntype OpenaiToolMeta = {\n \"openai/outputTemplate\": string;\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n \"openai/fileParams\"?: string[];\n};\n\n/** @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#resource-discovery */\ntype McpAppsToolMeta = {\n ui: McpUiToolMeta;\n};\n\ntype InternalToolMeta = Partial<OpenaiToolMeta & McpAppsToolMeta>;\n\n/** @see https://developers.openai.com/apps-sdk/reference#component-resource-_meta-fields */\ntype OpenaiViewCSP = {\n connect_domains: string[];\n resource_domains: string[];\n frame_domains?: string[];\n redirect_domains?: string[];\n};\n\ntype OpenaiResourceMeta = {\n \"openai/widgetDescription\"?: string;\n \"openai/widgetPrefersBorder\"?: boolean;\n \"openai/widgetCSP\"?: OpenaiViewCSP;\n \"openai/widgetDomain\"?: string;\n};\n\n/**\n * MCP Apps CSP extended with upcoming / Skybridge-specific fields.\n * @see https://github.com/modelcontextprotocol/ext-apps/pull/158\n */\ntype ExtendedMcpUiResourceCsp = McpUiResourceMeta[\"csp\"] & {\n /**\n * Origins that can receive openExternal redirects without the safe-link modal.\n * OpenAI-specific; mirrored into the mcp-apps CSP for cross-host parity.\n * @see https://developers.openai.com/apps-sdk/reference#component-resource-_meta-fields\n */\n redirectDomains?: string[];\n};\n\ntype ExtendedMcpUiResourceMeta = Omit<McpUiResourceMeta, \"csp\"> & {\n csp?: ExtendedMcpUiResourceCsp;\n};\n\ntype McpAppsResourceMeta = {\n ui?: ExtendedMcpUiResourceMeta;\n};\n\ntype ResourceMeta = OpenaiResourceMeta | McpAppsResourceMeta;\n\ntype ViewResourceConfig<T extends ResourceMeta = ResourceMeta> = {\n hostType: ViewHostType;\n uri: string;\n mimeType: string;\n buildContentMeta: (\n defaults: {\n resourceDomains: string[];\n connectDomains: string[];\n domain: string;\n baseUriDomains: string[];\n },\n overrides: { domain?: string },\n ) => T;\n};\n\n/**\n * Type-level marker interface for cross-package type inference.\n *\n * Consumers infer tool types via the structural `$types` property rather than\n * the `McpServer` class generic, because class-generic inference breaks when\n * `McpServer` comes from different package installations (e.g. a consumer\n * with its own `skybridge` dep vs. the in-tree workspace version).\n *\n * Inspired by tRPC's `_def` pattern and Hono's type markers.\n */\nexport interface McpServerTypes<TTools extends Record<string, ToolDef>> {\n readonly tools: TTools;\n}\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype ShapeOutput<Shape extends ZodRawShapeCompat> = Simplify<\n {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n }\n>;\n\ntype ExtractStructuredContent<T> = T extends { structuredContent: infer SC }\n ? Simplify<SC>\n : never;\n\ntype ExtractMeta<T> = [Extract<T, { _meta: unknown }>] extends [never]\n ? unknown\n : Extract<T, { _meta: unknown }> extends { _meta: infer M }\n ? Simplify<M>\n : unknown;\n\ntype AddTool<\n TTools,\n TName extends string,\n TInput extends ZodRawShapeCompat,\n TOutput,\n TResponseMetadata = unknown,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n }\n>;\n\ninterface ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: ZodRawShapeCompat | AnySchema;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n _meta?: ToolMeta;\n}\n\n/**\n * Optional client-supplied hints attached to `params._meta` on every tool call\n * by the Apps SDK host. Hints only: never use for authorization, and tolerate\n * absence.\n * @see https://developers.openai.com/apps-sdk/reference#_meta-fields-the-client-provides\n */\nexport interface ClientHintsMeta {\n /** Requested locale (BCP-47, e.g. `\"en-US\"`). */\n \"openai/locale\"?: string;\n /** Browser user-agent */\n \"openai/userAgent\"?: string;\n /** Coarse user location. May be partially populated. */\n \"openai/userLocation\"?: {\n city?: string;\n region?: string;\n country?: string;\n timezone?: string;\n longitude?: number;\n latitude?: number;\n };\n /** Anonymized user id. */\n \"openai/subject\"?: string;\n /** Anonymized conversation id, stable within a ChatGPT session. */\n \"openai/session\"?: string;\n /** Anonymized organization id, when the user account is part of an organization. */\n \"openai/organization\"?: string;\n /** Stable id for the currently mounted widget instance. */\n \"openai/widgetSessionId\"?: string;\n}\n\ntype ToolHandlerExtra = Omit<\n RequestHandlerExtra<ServerRequest, ServerNotification>,\n \"_meta\"\n> & {\n _meta?: RequestMeta & ClientHintsMeta;\n};\n\ntype ToolHandler<\n TInput extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent } = { content?: HandlerContent },\n> = (\n args: ShapeOutput<TInput>,\n extra: ToolHandlerExtra,\n) => TReturn | Promise<TReturn>;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\nexport function normalizeContent(\n content: HandlerContent | undefined,\n): ContentBlock[] {\n if (content === undefined) {\n return [];\n }\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n if (Array.isArray(content)) {\n return content;\n }\n return [content];\n}\n\n// We Omit `registerTool` from the base class at the type level so our\n// unified 2-arg signature can replace the SDK's 3-arg one without an\n// incompatible override. The runtime prototype chain is unaffected.\ninterface McpServerBaseOmitted\n extends Omit<McpServerBase, \"registerTool\" | \"connect\"> {}\nconst McpServerBaseOmitted = McpServerBase as unknown as new (\n ...args: ConstructorParameters<typeof McpServerBase>\n) => McpServerBaseOmitted;\n\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `server.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied. Register your handlers before `run()`;\n * after `run()`, dev-mode middleware, the `/mcp` route, and the default\n * error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n readonly express: Express;\n private customErrorMiddleware: ErrorMiddlewareConfig[] = [];\n private mcpMiddlewareEntries: McpMiddlewareEntry[] = [];\n private mcpMiddlewareApplied = false;\n private claimedViews = new Map<string, string>();\n private viteManifest: Record<string, ViteManifestEntry> | null = null;\n private readonly serverInfo: Implementation;\n private readonly serverOptions?: ServerOptions;\n\n constructor(serverInfo: Implementation, options?: ServerOptions) {\n super(serverInfo, options);\n this.serverInfo = serverInfo;\n this.serverOptions = options;\n this.express = express();\n this.express.use(express.json());\n }\n\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.express.use(pathOrHandler, ...handlers);\n } else {\n this.express.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.customErrorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.customErrorMiddleware.push({\n handlers: [pathOrHandler, ...handlers],\n });\n }\n return this;\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn): this;\n /** Register MCP protocol-level middleware for all requests (`extra` is `McpExtra`). */\n mcpMiddleware(\n filter: \"request\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtra,\n next: () => Promise<ServerResult>,\n ) => Promise<unknown> | unknown,\n ): this;\n /** Register MCP protocol-level middleware for all notifications (`extra` is `undefined`). */\n mcpMiddleware(\n filter: \"notification\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: undefined,\n next: () => Promise<undefined>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware for an exact method.\n * Narrows `params`, `extra`, and `next()` result based on the method string.\n */\n mcpMiddleware<M extends McpMethodString>(\n filter: M,\n handler: McpTypedMiddlewareFn<M>,\n ): this;\n /**\n * Register MCP protocol-level middleware for a wildcard pattern (e.g. `\"tools/*\"`).\n * `next()` returns the union of result types for matching methods.\n */\n mcpMiddleware<W extends McpWildcard>(\n filter: W,\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtraFor<W>,\n next: () => Promise<McpResultFor<W>>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware with a method filter.\n * Filter can be an exact method (`\"tools/call\"`), wildcard (`\"tools/*\"`),\n * category (`\"request\"` | `\"notification\"`), or an array of those.\n */\n mcpMiddleware(filter: McpMiddlewareFilter, handler: McpMiddlewareFn): this;\n mcpMiddleware(\n filterOrHandler: McpMiddlewareFilter | McpMiddlewareFn,\n // biome-ignore lint/suspicious/noExplicitAny: overloads narrow the handler type at call sites; implementation must accept all variants\n maybeHandler?: any,\n ): this {\n if (this.mcpMiddlewareApplied) {\n throw new Error(\n \"Cannot register MCP middleware after run() or connect() has been called\",\n );\n }\n\n const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.mcpMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler,\n });\n } else if (handler) {\n this.mcpMiddlewareEntries.push({\n filter: filterOrHandler,\n handler,\n });\n } else {\n throw new Error(\n \"mcpMiddleware requires a handler function when a filter is provided\",\n );\n }\n\n return this;\n }\n\n private applyMcpMiddleware(): void {\n if (this.mcpMiddlewareApplied) {\n return;\n }\n this.mcpMiddlewareApplied = true;\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = monitoringEntry\n ? [monitoringEntry, ...this.mcpMiddlewareEntries]\n : this.mcpMiddlewareEntries;\n\n if (entries.length === 0) {\n return;\n }\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n\n async connect(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n return McpServerBase.prototype.connect.call(this, transport);\n }\n\n /**\n * Per-request stateless connect. The SDK's `Protocol` only allows one\n * transport per instance, so we can't reuse this `McpServer` across\n * concurrent requests. The SDK's idiomatic fix is a `() => McpServer`\n * factory, but that would break Skybridge's singleton API — so instead\n * we build a fresh underlying `Server` per request and share the main\n * server's handler maps by reference. The cast is unavoidable: there's\n * no public API to inject handler maps. `getHandlerMaps` validates the\n * read side and fails fast on SDK field renames.\n */\n async connectStatelessTransport(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n const fresh = new SdkServer(this.serverInfo, this.serverOptions);\n const target = fresh as unknown as {\n _requestHandlers: unknown;\n _notificationHandlers: unknown;\n };\n target._requestHandlers = requestHandlers;\n target._notificationHandlers = notificationHandlers;\n\n await fresh.connect(transport);\n }\n\n async run(): Promise<{ fetch: (...args: unknown[]) => unknown } | undefined> {\n this.applyMcpMiddleware();\n const httpServer = http.createServer();\n\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n\n httpServer.on(\"request\", this.express);\n const port = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(port, () => {\n resolve();\n });\n });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private enforceOneToolPerView(component: string, toolName: string): void {\n const existingTool = this.claimedViews.get(component);\n if (existingTool) {\n throw new Error(\n `skybridge: view \"${component}\" is already used by tool \"${existingTool}\". Tool \"${toolName}\" cannot also reference it — each view backs exactly one tool.`,\n );\n }\n this.claimedViews.set(component, toolName);\n }\n\n private registerViewResources(\n toolName: string,\n view: ViewConfig,\n toolMeta: InternalToolMeta,\n ): void {\n const hosts = view.hosts ?? ([\"apps-sdk\", \"mcp-app\"] as const);\n\n // Append a content-derived version param so hosts (e.g. ChatGPT) bust\n // their cache when the bundle changes, but keep the URI stable across\n // `tools/list` calls when the bundle hasn't changed.\n const versionParam = this.computeViewVersionParam(view.component);\n\n if (hosts.includes(\"apps-sdk\")) {\n const viewResource: ViewResourceConfig<OpenaiResourceMeta> = {\n hostType: \"apps-sdk\",\n uri: `ui://views/apps-sdk/${view.component}.html${versionParam}`,\n mimeType: \"text/html+skybridge\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain },\n overrides,\n ) => {\n const defaults: OpenaiResourceMeta = {\n \"openai/widgetCSP\": {\n resource_domains: resourceDomains,\n connect_domains: connectDomains,\n },\n \"openai/widgetDomain\": domain,\n \"openai/widgetDescription\": view.description,\n };\n\n const fromView: Partial<\n Omit<\n OpenaiResourceMeta,\n \"openai/widgetCSP\" | \"openai/widgetDescription\"\n > & {\n \"openai/widgetCSP\": Partial<OpenaiViewCSP>;\n }\n > = {\n \"openai/widgetCSP\": {\n resource_domains: view.csp?.resourceDomains,\n connect_domains: view.csp?.connectDomains,\n frame_domains: view.csp?.frameDomains,\n redirect_domains: view.csp?.redirectDomains,\n },\n \"openai/widgetDomain\": view.domain,\n \"openai/widgetPrefersBorder\": view.prefersBorder,\n };\n\n const base = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n \"openai/widgetDomain\": overrides.domain,\n });\n\n if (view._meta) {\n return { ...base, ...view._meta } as OpenaiResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({\n name: toolName,\n viewResource,\n view,\n });\n toolMeta[\"openai/outputTemplate\"] = viewResource.uri;\n }\n\n if (hosts.includes(\"mcp-app\")) {\n const viewResource: ViewResourceConfig<McpAppsResourceMeta> = {\n hostType: \"mcp-app\",\n uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,\n mimeType: \"text/html;profile=mcp-app\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain, baseUriDomains },\n overrides,\n ) => {\n const defaults: McpAppsResourceMeta = {\n ui: {\n csp: {\n resourceDomains,\n connectDomains,\n baseUriDomains,\n },\n domain,\n },\n };\n\n const fromView: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n ...(view.domain && { domain: view.domain }),\n csp: {\n ...(view.csp?.resourceDomains && {\n resourceDomains: view.csp.resourceDomains,\n }),\n ...(view.csp?.connectDomains && {\n connectDomains: view.csp.connectDomains,\n }),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n ...(view.csp?.baseUriDomains && {\n baseUriDomains: view.csp.baseUriDomains,\n }),\n ...(view.csp?.redirectDomains && {\n redirectDomains: view.csp.redirectDomains,\n }),\n },\n },\n };\n\n const base = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n ui: overrides,\n });\n\n if (view._meta) {\n return { ...base, ...view._meta } as McpAppsResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({\n name: toolName,\n viewResource,\n view,\n });\n // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs\n toolMeta[\"ui/resourceUri\"] = viewResource.uri;\n\n toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };\n }\n }\n\n private registerViewResource({\n name,\n viewResource,\n view,\n }: {\n name: string;\n viewResource: ViewResourceConfig;\n view: ViewConfig;\n }): void {\n const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;\n\n this.registerResource(\n name,\n viewUri,\n { description: view.description },\n async (uri, extra) => {\n const isProduction = process.env.NODE_ENV === \"production\";\n const isClaude =\n extra?.requestInfo?.headers?.[\"user-agent\"] === \"Claude-User\";\n\n const headers = extra?.requestInfo?.headers || {};\n const header = (key: string) => {\n const val = headers[key];\n return Array.isArray(val) ? val[0] : val;\n };\n\n let serverUrl: string;\n\n const forwardedHost = header(\"x-forwarded-host\");\n const origin = header(\"origin\");\n const host = header(\"host\");\n\n if (forwardedHost) {\n const proto = header(\"x-forwarded-proto\") || \"https\";\n serverUrl = `${proto}://${forwardedHost}`;\n } else if (origin) {\n serverUrl = origin;\n } else if (host) {\n const proto = [\"127.0.0.1:\", \"localhost:\"].some((p) =>\n host.startsWith(p),\n )\n ? \"http\"\n : \"https\";\n serverUrl = `${proto}://${host}`;\n } else {\n const devPort = process.env.__PORT || \"3000\";\n serverUrl = `http://localhost:${devPort}`;\n }\n\n const html = isProduction\n ? templateHelper.renderProduction({\n hostType,\n serverUrl,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\n hostType,\n serverUrl,\n viewName: view.component,\n });\n\n const connectDomains = [serverUrl];\n if (!isProduction) {\n const wsUrl = new URL(serverUrl);\n wsUrl.protocol = wsUrl.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n connectDomains.push(wsUrl.origin);\n }\n\n let contentMetaOverrides: { domain?: string } = {};\n if (isClaude) {\n const pathname = extra?.requestInfo?.url?.pathname ?? \"\";\n const rawUrl =\n header(\"x-alpic-forwarded-url\") ?? `${serverUrl}${pathname}`;\n // Strip a lone trailing slash so the hash matches the connector URL\n // as registered with Claude (which has no trailing slash on bare origins).\n const url = rawUrl.endsWith(\"/\") ? rawUrl.slice(0, -1) : rawUrl;\n const hash = crypto\n .createHash(\"sha256\")\n .update(url)\n .digest(\"hex\")\n .slice(0, 32);\n contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };\n }\n\n const contentMeta = buildContentMeta(\n {\n resourceDomains: [serverUrl],\n connectDomains,\n domain: serverUrl,\n baseUriDomains: [serverUrl],\n },\n contentMetaOverrides,\n );\n\n return {\n contents: [\n { uri: uri.href, mimeType, text: html, _meta: contentMeta },\n ],\n };\n },\n );\n }\n\n private wrapHandler<InputArgs extends ZodRawShapeCompat>(\n cb: ToolHandler<InputArgs>,\n { attachViewUUID }: { attachViewUUID: boolean },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n const result = await cb(args, extra);\n return {\n ...result,\n content: normalizeContent(result.content),\n ...(attachViewUUID && {\n _meta: {\n ...(result as { _meta?: Record<string, unknown> })._meta,\n viewUUID: crypto.randomUUID(),\n },\n }),\n };\n };\n }\n\n private computeViewVersionParam(viewName: string): string {\n if (process.env.NODE_ENV !== \"production\") {\n return \"\";\n }\n try {\n const viewFile = this.lookupViewFile(viewName);\n const styleFile = this.lookupDistFile(\"style.css\") ?? \"\";\n const hash = crypto\n .createHash(\"sha256\")\n .update(viewFile)\n .update(\"\\0\")\n .update(styleFile)\n .digest(\"hex\")\n .slice(0, 8);\n return `?v=${hash}`;\n } catch {\n return \"\";\n }\n }\n\n private lookupViewFile(viewName: string) {\n const manifest = this.readManifest();\n for (const entry of Object.values(manifest)) {\n if (entry?.isEntry && entry.name === viewName && entry.file) {\n return entry.file;\n }\n }\n throw new Error(\n `View \"${viewName}\" not found in Vite manifest. Did the build complete successfully? Look for an entry with name \"${viewName}\" in dist/assets/.vite/manifest.json.`,\n );\n }\n\n private lookupDistFile(key: string) {\n const manifest = this.readManifest();\n return manifest[key]?.file;\n }\n\n /**\n * Inject the Vite manifest as a value rather than letting `readManifest()`\n * load it from disk. Required for runtimes without a usable filesystem\n * (Cloudflare Workers, etc.) — the user's `skybridge build` emits the\n * manifest as a JS module which the entry imports and passes here.\n */\n setViteManifest(manifest: Record<string, { file: string }>): this {\n this.viteManifest = manifest as Record<string, ViteManifestEntry>;\n return this;\n }\n\n private readManifest(): Record<string, ViteManifestEntry> {\n if (this.viteManifest) {\n return this.viteManifest;\n }\n return JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n }\n\n registerTool<\n TName extends string,\n InputArgs extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>\n >;\n registerTool<InputArgs extends ZodRawShapeCompat>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs>,\n ): this;\n registerTool(...args: unknown[]): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n if (typeof args[0] === \"string\") {\n baseFn.call(this, args[0], args[1], args[2]);\n return this;\n }\n\n const config = args[0] as ToolConfig<ZodRawShapeCompat>;\n const cb = args[1] as ToolHandler<ZodRawShapeCompat>;\n\n const { name, view, _meta: userToolMeta, ...toolFields } = config;\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n if (view) {\n this.enforceOneToolPerView(view.component, name);\n this.registerViewResources(name, view, toolMeta);\n }\n\n const wrappedCb = this.wrapHandler(cb, { attachViewUUID: Boolean(view) });\n\n baseFn.call(this, name, { ...toolFields, _meta: toolMeta }, wrappedCb);\n\n return this;\n }\n}\n"]}
@@ -30,7 +30,13 @@ export class AppsSdkAdaptor {
30
30
  };
31
31
  }
32
32
  callTool = async (name, args) => {
33
- return window.openai.callTool(name, args);
33
+ const response = await window.openai.callTool(name, args);
34
+ return {
35
+ content: response.content,
36
+ structuredContent: response.structuredContent ?? {},
37
+ isError: response.isError ?? false,
38
+ meta: response._meta ?? response.meta ?? {},
39
+ };
34
40
  };
35
41
  requestDisplayMode = (mode) => {
36
42
  return window.openai.requestDisplayMode({ mode });
@@ -1 +1 @@
1
- {"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/adaptor.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,OAAO,cAAc;IACjB,MAAM,CAAC,QAAQ,GAA0B,IAAI,CAAC;IAE/C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC;YAC7B,cAAc,CAAC,QAAQ,GAAG,IAAI,cAAc,EAAE,CAAC;QACjD,CAAC;QACD,OAAO,cAAc,CAAC,QAAQ,CAAC;IACjC,CAAC;IAEM,MAAM,CAAC,aAAa;QACzB,cAAc,CAAC,QAAQ,GAAG,IAAI,CAAC;IACjC,CAAC;IAEM,mBAAmB,CACxB,GAAM;QAEN,MAAM,MAAM,GAAG,aAAa,CAAC,WAAW,EAAE,CA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,EAAE,CAAC;QAChD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;QACzD,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEM,KAAK,CAAC,YAAY,CAAC,GAAG,OAAiB;QAC7C,MAAM,KAAK,GAAuB,MAAM,CAAC,MAAM,CAAC,WAAW;YACzD,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;YAClC,CAAC,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;QAC7C,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;YACpB,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC;QACtB,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC;QAChC,MAAM,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAEM,SAAS,CAAC,OAA4B;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IAEM,eAAe,CAAC,IAAY;QACjC,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAEnB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC","sourcesContent":["import type {\n Adaptor,\n CallToolResponse,\n FileMetadata,\n HostContext,\n HostContextStore,\n OpenExternalOptions,\n RequestDisplayMode,\n RequestModalOptions,\n RequestSizeOptions,\n SendFollowUpMessageOptions,\n SetViewStateAction,\n UploadFileOptions,\n} from \"../types.js\";\nimport { AppsSdkBridge } from \"./bridge.js\";\nimport type { AppsSdkWidgetState } from \"./types.js\";\n\nexport class AppsSdkAdaptor implements Adaptor {\n private static instance: AppsSdkAdaptor | null = null;\n\n public static getInstance(): AppsSdkAdaptor {\n if (!AppsSdkAdaptor.instance) {\n AppsSdkAdaptor.instance = new AppsSdkAdaptor();\n }\n return AppsSdkAdaptor.instance;\n }\n\n public static resetInstance(): void {\n AppsSdkAdaptor.instance = null;\n }\n\n public getHostContextStore<K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> {\n const bridge = AppsSdkBridge.getInstance();\n\n if (key === \"viewState\") {\n return {\n subscribe: bridge.subscribe(\"widgetState\"),\n getSnapshot: () =>\n bridge.getSnapshot(\"widgetState\")?.modelContent ?? null,\n } as HostContextStore<K>;\n }\n\n if (key === \"display\") {\n return {\n subscribe: bridge.subscribe(\"view\"),\n getSnapshot: () => bridge.getSnapshot(\"view\"),\n } as HostContextStore<K>;\n }\n\n return {\n subscribe: bridge.subscribe(key),\n getSnapshot: () => bridge.getSnapshot(key),\n } as HostContextStore<K>;\n }\n\n public callTool = async <\n ToolArgs extends Record<string, unknown> | null = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(\n name: string,\n args: ToolArgs,\n ): Promise<ToolResponse> => {\n return window.openai.callTool<ToolArgs, ToolResponse>(name, args);\n };\n\n public requestDisplayMode = (\n mode: RequestDisplayMode,\n ): Promise<{ mode: RequestDisplayMode }> => {\n return window.openai.requestDisplayMode({ mode });\n };\n\n public requestClose = (): Promise<void> => {\n return window.openai.requestClose();\n };\n\n public requestSize = async (_size: RequestSizeOptions): Promise<void> => {\n console.warn(\"[skybridge] requestSize: not supported on Apps SDK\");\n };\n\n public sendFollowUpMessage = (\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void> => {\n return window.openai.sendFollowUpMessage({\n prompt,\n scrollToBottom: options?.scrollToBottom,\n });\n };\n\n public openExternal(href: string, options: OpenExternalOptions = {}): void {\n window.openai.openExternal({ href, ...options });\n }\n\n public setViewState = (stateOrUpdater: SetViewStateAction): Promise<void> => {\n const modelContent =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(window.openai.widgetState?.modelContent ?? null)\n : stateOrUpdater;\n\n return window.openai.setWidgetState({\n privateContent: {},\n ...window.openai.widgetState,\n modelContent,\n });\n };\n\n public uploadFile = async (file: File, options?: UploadFileOptions) => {\n const metadata = await window.openai.uploadFile(file, options);\n await this.trackFileIds(metadata.fileId);\n return metadata;\n };\n\n public getFileDownloadUrl = (file: { fileId: string }) => {\n return window.openai.getFileDownloadUrl(file);\n };\n\n public selectFiles = async (): Promise<FileMetadata[]> => {\n if (!window.openai.selectFiles) {\n throw new Error(\n \"selectFiles is not supported by the current host version.\",\n );\n }\n const files = await window.openai.selectFiles();\n if (files.length > 0) {\n await this.trackFileIds(...files.map((f) => f.fileId));\n }\n return files;\n };\n\n private async trackFileIds(...fileIds: string[]): Promise<void> {\n const state: AppsSdkWidgetState = window.openai.widgetState\n ? { ...window.openai.widgetState }\n : { modelContent: {}, privateContent: {} };\n if (!state.imageIds) {\n state.imageIds = [];\n }\n state.imageIds.push(...fileIds);\n await window.openai.setWidgetState(state);\n }\n\n public openModal(options: RequestModalOptions) {\n return window.openai.requestModal(options);\n }\n\n public setOpenInAppUrl(href: string): Promise<void> {\n href = href.trim();\n\n if (!href) {\n throw new Error(\"The href parameter is required.\");\n }\n\n return window.openai.setOpenInAppUrl({ href });\n }\n}\n"]}
1
+ {"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/adaptor.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,OAAO,cAAc;IACjB,MAAM,CAAC,QAAQ,GAA0B,IAAI,CAAC;IAE/C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,cAA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MAAM,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAEM,SAAS,CAAC,OAA4B;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IAEM,eAAe,CAAC,IAAY;QACjC,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAEnB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC","sourcesContent":["import type {\n Adaptor,\n CallToolResponse,\n FileMetadata,\n HostContext,\n HostContextStore,\n OpenExternalOptions,\n RequestDisplayMode,\n RequestModalOptions,\n RequestSizeOptions,\n SendFollowUpMessageOptions,\n SetViewStateAction,\n UploadFileOptions,\n} from \"../types.js\";\nimport { AppsSdkBridge } from \"./bridge.js\";\nimport type { AppsSdkWidgetState } from \"./types.js\";\n\nexport class AppsSdkAdaptor implements Adaptor {\n private static instance: AppsSdkAdaptor | null = null;\n\n public static getInstance(): AppsSdkAdaptor {\n if (!AppsSdkAdaptor.instance) {\n AppsSdkAdaptor.instance = new AppsSdkAdaptor();\n }\n return AppsSdkAdaptor.instance;\n }\n\n public static resetInstance(): void {\n AppsSdkAdaptor.instance = null;\n }\n\n public getHostContextStore<K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> {\n const bridge = AppsSdkBridge.getInstance();\n\n if (key === \"viewState\") {\n return {\n subscribe: bridge.subscribe(\"widgetState\"),\n getSnapshot: () =>\n bridge.getSnapshot(\"widgetState\")?.modelContent ?? null,\n } as HostContextStore<K>;\n }\n\n if (key === \"display\") {\n return {\n subscribe: bridge.subscribe(\"view\"),\n getSnapshot: () => bridge.getSnapshot(\"view\"),\n } as HostContextStore<K>;\n }\n\n return {\n subscribe: bridge.subscribe(key),\n getSnapshot: () => bridge.getSnapshot(key),\n } as HostContextStore<K>;\n }\n\n public callTool = async <\n ToolArgs extends Record<string, unknown> | null = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(\n name: string,\n args: ToolArgs,\n ): Promise<ToolResponse> => {\n const response = await (window.openai.callTool(name, args) as Promise<\n CallToolResponse & { _meta?: CallToolResponse[\"meta\"] }\n >);\n return {\n content: response.content,\n structuredContent: response.structuredContent ?? {},\n isError: response.isError ?? false,\n meta: response._meta ?? response.meta ?? {},\n } as ToolResponse;\n };\n\n public requestDisplayMode = (\n mode: RequestDisplayMode,\n ): Promise<{ mode: RequestDisplayMode }> => {\n return window.openai.requestDisplayMode({ mode });\n };\n\n public requestClose = (): Promise<void> => {\n return window.openai.requestClose();\n };\n\n public requestSize = async (_size: RequestSizeOptions): Promise<void> => {\n console.warn(\"[skybridge] requestSize: not supported on Apps SDK\");\n };\n\n public sendFollowUpMessage = (\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void> => {\n return window.openai.sendFollowUpMessage({\n prompt,\n scrollToBottom: options?.scrollToBottom,\n });\n };\n\n public openExternal(href: string, options: OpenExternalOptions = {}): void {\n window.openai.openExternal({ href, ...options });\n }\n\n public setViewState = (stateOrUpdater: SetViewStateAction): Promise<void> => {\n const modelContent =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(window.openai.widgetState?.modelContent ?? null)\n : stateOrUpdater;\n\n return window.openai.setWidgetState({\n privateContent: {},\n ...window.openai.widgetState,\n modelContent,\n });\n };\n\n public uploadFile = async (file: File, options?: UploadFileOptions) => {\n const metadata = await window.openai.uploadFile(file, options);\n await this.trackFileIds(metadata.fileId);\n return metadata;\n };\n\n public getFileDownloadUrl = (file: { fileId: string }) => {\n return window.openai.getFileDownloadUrl(file);\n };\n\n public selectFiles = async (): Promise<FileMetadata[]> => {\n if (!window.openai.selectFiles) {\n throw new Error(\n \"selectFiles is not supported by the current host version.\",\n );\n }\n const files = await window.openai.selectFiles();\n if (files.length > 0) {\n await this.trackFileIds(...files.map((f) => f.fileId));\n }\n return files;\n };\n\n private async trackFileIds(...fileIds: string[]): Promise<void> {\n const state: AppsSdkWidgetState = window.openai.widgetState\n ? { ...window.openai.widgetState }\n : { modelContent: {}, privateContent: {} };\n if (!state.imageIds) {\n state.imageIds = [];\n }\n state.imageIds.push(...fileIds);\n await window.openai.setWidgetState(state);\n }\n\n public openModal(options: RequestModalOptions) {\n return window.openai.requestModal(options);\n }\n\n public setOpenInAppUrl(href: string): Promise<void> {\n href = href.trim();\n\n if (!href) {\n throw new Error(\"The href parameter is required.\");\n }\n\n return window.openai.setOpenInAppUrl({ href });\n }\n}\n"]}
@@ -20,8 +20,27 @@ describe("useCallTool - onSuccess callback", () => {
20
20
  content: [{ type: "text", text: "test result" }],
21
21
  structuredContent: { result: "test" },
22
22
  isError: false,
23
+ meta: {},
23
24
  };
24
25
  const error = new Error("test error");
26
+ it("should normalize _meta to meta when SDK returns _meta instead of meta", async () => {
27
+ const rawSdkResponse = {
28
+ content: [{ type: "text", text: "result" }],
29
+ structuredContent: { value: 1 },
30
+ isError: false,
31
+ _meta: { secret: "only visible to widget" },
32
+ };
33
+ OpenaiMock.callTool.mockResolvedValueOnce(rawSdkResponse);
34
+ const { result } = renderHook(() => useCallTool(toolName));
35
+ await act(async () => {
36
+ result.current.callTool(args);
37
+ });
38
+ await waitFor(() => {
39
+ expect(result.current.data).toMatchObject({
40
+ meta: { secret: "only visible to widget" },
41
+ });
42
+ });
43
+ });
25
44
  it("should call window.openai.callTool with correct arguments", async () => {
26
45
  const { result } = renderHook(() => useCallTool(toolName));
27
46
  await act(async () => {
@@ -101,8 +120,14 @@ describe("useCallTool - onSuccess callback", () => {
101
120
  });
102
121
  it("should always return last call started state", async () => {
103
122
  const { result } = renderHook(() => useCallTool(toolName));
104
- const firstCallData = { ...data, result: "first call result" };
105
- const secondCallData = { ...data, result: "second call result" };
123
+ const firstCallData = {
124
+ ...data,
125
+ structuredContent: { result: "first call result" },
126
+ };
127
+ const secondCallData = {
128
+ ...data,
129
+ structuredContent: { result: "second call result" },
130
+ };
106
131
  const { promise: firstCallToolPromise, resolve: resolveFirstCallTool } = Promise.withResolvers();
107
132
  const { promise: secondCallToolPromise, resolve: resolveSecondCallTool } = Promise.withResolvers();
108
133
  OpenaiMock.callTool
@@ -1 +1 @@
1
- {"version":3,"file":"use-call-tool.test.js","sourceRoot":"","sources":["../../../src/web/hooks/use-call-tool.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,EAAE,EAEF,EAAE,GACH,MAAM,QAAQ,CAAC;AAGhB,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,QAAQ,CAAC,kCAAkC,EAAE,GAAG,EAAE;IAChD,IAAI,UAA8B,CAAC;IAEnC,UAAU,CAAC,GAAG,EAAE;QACd,UAAU,GAAG;YACX,QAAQ,EAAE,EAAE,CAAC,EAAE,EAAE;SAClB,CAAC;QACF,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;QACpC,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE;QACb,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACtB,EAAE,CAAC,aAAa,EAAE,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,WAAW,CAAC;IAC7B,MAAM,IAAI,GAAG,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;IACrC,MAAM,IAAI,GAAqB;QAC7B,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,aAAa,EA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AAe,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;YAClD,iBAAiB,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE;YACxC,OAAO,EAAE,KAAK;YACd,IAAI,EAAE,EAAE;SACT,CAAC;QAEF,UAAU,CAAC,QAAQ,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;QAExD,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,KAAK,IAAI,EAAE;YACzC,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;QACxC,CAAC,CAAC,CAAC;QACH,YAAY,CAAsB,aAAa,CAAC,CAAC;QACjD,MAAM,CAAC,aAAa,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { act, renderHook, waitFor } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n expectTypeOf,\n it,\n type Mock,\n vi,\n} from \"vitest\";\n\nimport type { CallToolResponse } from \"../bridges/types.js\";\nimport { useCallTool } from \"./use-call-tool.js\";\n\ndescribe(\"useCallTool - onSuccess callback\", () => {\n let OpenaiMock: { callTool: Mock };\n\n beforeEach(() => {\n OpenaiMock = {\n callTool: vi.fn(),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n const toolName = \"test-tool\";\n const args = { input: \"test input\" };\n const data: CallToolResponse = {\n content: [{ type: \"text\" as const, text: \"test result\" }],\n structuredContent: { result: \"test\" },\n isError: false,\n };\n const error = new Error(\"test error\");\n\n it(\"should call window.openai.callTool with correct arguments\", async () => {\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n await act(async () => {\n result.current.callTool(args);\n });\n expect(OpenaiMock.callTool).toHaveBeenCalledWith(toolName, args);\n });\n\n it(\"should call onSuccess callback with correct data and toolArgs on successful execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n OpenaiMock.callTool.mockResolvedValueOnce(data);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n });\n });\n\n await waitFor(() => {\n expect(onSuccess).toHaveBeenCalledWith(data, args);\n expect(onError).not.toHaveBeenCalled();\n });\n });\n\n it(\"should call onError callback with error and toolArgs on failed execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n OpenaiMock.callTool.mockRejectedValueOnce(error);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n });\n });\n\n await waitFor(() => {\n expect(onSuccess).not.toHaveBeenCalled();\n expect(onError).toHaveBeenCalledWith(error, args);\n });\n });\n\n it(\"should call onSettled callback with data and undefined error on successful execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n const onSettled = vi.fn();\n OpenaiMock.callTool.mockResolvedValueOnce(data);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n onSettled,\n });\n });\n\n await waitFor(() => {\n expect(onSuccess).toHaveBeenCalledWith(data, args);\n expect(onSettled).toHaveBeenCalledWith(data, undefined, args);\n expect(onError).not.toHaveBeenCalled();\n });\n });\n\n it(\"should call onSettled callback with undefined data and error on failed execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n const onSettled = vi.fn();\n OpenaiMock.callTool.mockRejectedValueOnce(error);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n onSettled,\n });\n });\n\n await waitFor(() => {\n expect(onError).toHaveBeenCalledWith(error, args);\n expect(onSettled).toHaveBeenCalledWith(undefined, error, args);\n expect(onSuccess).not.toHaveBeenCalled();\n });\n });\n\n it(\"should always return last call started state\", async () => {\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n const firstCallData = { ...data, result: \"first call result\" };\n const secondCallData = { ...data, result: \"second call result\" };\n const { promise: firstCallToolPromise, resolve: resolveFirstCallTool } =\n Promise.withResolvers();\n const { promise: secondCallToolPromise, resolve: resolveSecondCallTool } =\n Promise.withResolvers();\n OpenaiMock.callTool\n .mockImplementationOnce(() => firstCallToolPromise)\n .mockImplementationOnce(() => secondCallToolPromise);\n\n await act(() => {\n result.current.callTool(args);\n result.current.callTool(args);\n resolveFirstCallTool(firstCallData);\n return firstCallToolPromise;\n });\n\n expect(result.current.status).toEqual(\"pending\");\n expect(result.current.data).toEqual(undefined);\n resolveSecondCallTool(secondCallData);\n\n await waitFor(() => {\n expect(result.current.status).toEqual(\"success\");\n expect(result.current.data).toEqual(secondCallData);\n });\n });\n});\n\ndescribe(\"useCallTool - TypeScript typing\", () => {\n let OpenaiMock: { callTool: Mock };\n\n beforeEach(() => {\n OpenaiMock = {\n callTool: vi.fn(),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n it(\"should have correct return types when ToolArgs is null and ToolResponse is specified\", async () => {\n type TestResponse = CallToolResponse & {\n structuredContent: { result: string };\n meta: { id: number };\n };\n\n const { result } = renderHook(() =>\n useCallTool<null, TestResponse>(\"test-tool\"),\n );\n const data: TestResponse = {\n content: [{ type: \"text\" as const, text: \"test\" }],\n structuredContent: { result: \"test\" },\n isError: false,\n meta: { id: 123 },\n };\n\n OpenaiMock.callTool.mockResolvedValueOnce(data);\n\n await act(async () => {\n result.current.callTool();\n });\n\n expect(OpenaiMock.callTool).toHaveBeenCalledWith(\"test-tool\", null);\n expectTypeOf<typeof data | undefined>(result.current.data);\n });\n\n it(\"should correctly type callToolAsync return value\", async () => {\n type TestArgs = { query: string };\n type TestResponse = CallToolResponse & {\n structuredContent: { answer: string };\n };\n\n const { result } = renderHook(() =>\n useCallTool<TestArgs, TestResponse>(\"test-tool\"),\n );\n\n const testArgs: TestArgs = { query: \"test\" };\n const mockResponse: TestResponse = {\n content: [{ type: \"text\" as const, text: \"answer\" }],\n structuredContent: { answer: \"test answer\" },\n isError: false,\n meta: {},\n };\n\n OpenaiMock.callTool.mockResolvedValueOnce(mockResponse);\n\n const returnedValue = await act(async () => {\n return result.current.callToolAsync(testArgs);\n });\n expectTypeOf<typeof mockResponse>(returnedValue);\n expect(returnedValue).toEqual(mockResponse);\n });\n\n it(\"should correctly type callToolAsync when ToolArgs is null\", async () => {\n type TestResponse = CallToolResponse & {\n structuredContent: { data: string };\n };\n\n const { result } = renderHook(() =>\n useCallTool<null, TestResponse>(\"test-tool\"),\n );\n\n const mockResponse: TestResponse = {\n content: [{ type: \"text\" as const, text: \"data\" }],\n structuredContent: { data: \"test data\" },\n isError: false,\n meta: {},\n };\n\n OpenaiMock.callTool.mockResolvedValueOnce(mockResponse);\n\n const returnedValue = await act(async () => {\n return result.current.callToolAsync();\n });\n expectTypeOf<typeof mockResponse>(returnedValue);\n expect(returnedValue).toEqual(mockResponse);\n });\n});\n"]}
1
+ {"version":3,"file":"use-call-tool.test.js","sourceRoot":"","sources":["../../../src/web/hooks/use-call-tool.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,EAAE,EAEF,EAAE,GACH,MAAM,QAAQ,CAAC;AAGhB,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,QAAQ,CAAC,kCAAkC,EAAE,GAAG,EAAE;IAChD,IAAI,UAA8B,CAAC;IAEnC,UAAU,CA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AC,CAAC,CAAC;IAEH,EAAE,CAAC,2DAA2D,EAAE,KAAK,IAAI,EAAE;QAKzE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC,GAAG,EAAE,CACjC,WAAW,CAAqB,WAAW,CAAC,CAC7C,CAAC;QAEF,MAAM,YAAY,GAAiB;YACjC,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;YAClD,iBAAiB,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE;YACxC,OAAO,EAAE,KAAK;YACd,IAAI,EAAE,EAAE;SACT,CAAC;QAEF,UAAU,CAAC,QAAQ,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;QAExD,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,KAAK,IAAI,EAAE;YACzC,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;QACxC,CAAC,CAAC,CAAC;QACH,YAAY,CAAsB,aAAa,CAAC,CAAC;QACjD,MAAM,CAAC,aAAa,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC9C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { act, renderHook, waitFor } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n expectTypeOf,\n it,\n type Mock,\n vi,\n} from \"vitest\";\n\nimport type { CallToolResponse } from \"../bridges/types.js\";\nimport { useCallTool } from \"./use-call-tool.js\";\n\ndescribe(\"useCallTool - onSuccess callback\", () => {\n let OpenaiMock: { callTool: Mock };\n\n beforeEach(() => {\n OpenaiMock = {\n callTool: vi.fn(),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n const toolName = \"test-tool\";\n const args = { input: \"test input\" };\n const data: CallToolResponse = {\n content: [{ type: \"text\" as const, text: \"test result\" }],\n structuredContent: { result: \"test\" },\n isError: false,\n meta: {},\n };\n const error = new Error(\"test error\");\n\n it(\"should normalize _meta to meta when SDK returns _meta instead of meta\", async () => {\n const rawSdkResponse = {\n content: [{ type: \"text\" as const, text: \"result\" }],\n structuredContent: { value: 1 },\n isError: false,\n _meta: { secret: \"only visible to widget\" },\n };\n OpenaiMock.callTool.mockResolvedValueOnce(rawSdkResponse);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n await act(async () => {\n result.current.callTool(args);\n });\n\n await waitFor(() => {\n expect(result.current.data).toMatchObject({\n meta: { secret: \"only visible to widget\" },\n });\n });\n });\n\n it(\"should call window.openai.callTool with correct arguments\", async () => {\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n await act(async () => {\n result.current.callTool(args);\n });\n expect(OpenaiMock.callTool).toHaveBeenCalledWith(toolName, args);\n });\n\n it(\"should call onSuccess callback with correct data and toolArgs on successful execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n OpenaiMock.callTool.mockResolvedValueOnce(data);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n });\n });\n\n await waitFor(() => {\n expect(onSuccess).toHaveBeenCalledWith(data, args);\n expect(onError).not.toHaveBeenCalled();\n });\n });\n\n it(\"should call onError callback with error and toolArgs on failed execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n OpenaiMock.callTool.mockRejectedValueOnce(error);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n });\n });\n\n await waitFor(() => {\n expect(onSuccess).not.toHaveBeenCalled();\n expect(onError).toHaveBeenCalledWith(error, args);\n });\n });\n\n it(\"should call onSettled callback with data and undefined error on successful execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n const onSettled = vi.fn();\n OpenaiMock.callTool.mockResolvedValueOnce(data);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n onSettled,\n });\n });\n\n await waitFor(() => {\n expect(onSuccess).toHaveBeenCalledWith(data, args);\n expect(onSettled).toHaveBeenCalledWith(data, undefined, args);\n expect(onError).not.toHaveBeenCalled();\n });\n });\n\n it(\"should call onSettled callback with undefined data and error on failed execution\", async () => {\n const onSuccess = vi.fn();\n const onError = vi.fn();\n const onSettled = vi.fn();\n OpenaiMock.callTool.mockRejectedValueOnce(error);\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n act(() => {\n result.current.callTool(args, {\n onSuccess,\n onError,\n onSettled,\n });\n });\n\n await waitFor(() => {\n expect(onError).toHaveBeenCalledWith(error, args);\n expect(onSettled).toHaveBeenCalledWith(undefined, error, args);\n expect(onSuccess).not.toHaveBeenCalled();\n });\n });\n\n it(\"should always return last call started state\", async () => {\n const { result } = renderHook(() =>\n useCallTool<typeof args, typeof data>(toolName),\n );\n\n const firstCallData = {\n ...data,\n structuredContent: { result: \"first call result\" },\n };\n const secondCallData = {\n ...data,\n structuredContent: { result: \"second call result\" },\n };\n const { promise: firstCallToolPromise, resolve: resolveFirstCallTool } =\n Promise.withResolvers();\n const { promise: secondCallToolPromise, resolve: resolveSecondCallTool } =\n Promise.withResolvers();\n OpenaiMock.callTool\n .mockImplementationOnce(() => firstCallToolPromise)\n .mockImplementationOnce(() => secondCallToolPromise);\n\n await act(() => {\n result.current.callTool(args);\n result.current.callTool(args);\n resolveFirstCallTool(firstCallData);\n return firstCallToolPromise;\n });\n\n expect(result.current.status).toEqual(\"pending\");\n expect(result.current.data).toEqual(undefined);\n resolveSecondCallTool(secondCallData);\n\n await waitFor(() => {\n expect(result.current.status).toEqual(\"success\");\n expect(result.current.data).toEqual(secondCallData);\n });\n });\n});\n\ndescribe(\"useCallTool - TypeScript typing\", () => {\n let OpenaiMock: { callTool: Mock };\n\n beforeEach(() => {\n OpenaiMock = {\n callTool: vi.fn(),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n it(\"should have correct return types when ToolArgs is null and ToolResponse is specified\", async () => {\n type TestResponse = CallToolResponse & {\n structuredContent: { result: string };\n meta: { id: number };\n };\n\n const { result } = renderHook(() =>\n useCallTool<null, TestResponse>(\"test-tool\"),\n );\n const data: TestResponse = {\n content: [{ type: \"text\" as const, text: \"test\" }],\n structuredContent: { result: \"test\" },\n isError: false,\n meta: { id: 123 },\n };\n\n OpenaiMock.callTool.mockResolvedValueOnce(data);\n\n await act(async () => {\n result.current.callTool();\n });\n\n expect(OpenaiMock.callTool).toHaveBeenCalledWith(\"test-tool\", null);\n expectTypeOf<typeof data | undefined>(result.current.data);\n });\n\n it(\"should correctly type callToolAsync return value\", async () => {\n type TestArgs = { query: string };\n type TestResponse = CallToolResponse & {\n structuredContent: { answer: string };\n };\n\n const { result } = renderHook(() =>\n useCallTool<TestArgs, TestResponse>(\"test-tool\"),\n );\n\n const testArgs: TestArgs = { query: \"test\" };\n const mockResponse: TestResponse = {\n content: [{ type: \"text\" as const, text: \"answer\" }],\n structuredContent: { answer: \"test answer\" },\n isError: false,\n meta: {},\n };\n\n OpenaiMock.callTool.mockResolvedValueOnce(mockResponse);\n\n const returnedValue = await act(async () => {\n return result.current.callToolAsync(testArgs);\n });\n expectTypeOf<typeof mockResponse>(returnedValue);\n expect(returnedValue).toEqual(mockResponse);\n });\n\n it(\"should correctly type callToolAsync when ToolArgs is null\", async () => {\n type TestResponse = CallToolResponse & {\n structuredContent: { data: string };\n };\n\n const { result } = renderHook(() =>\n useCallTool<null, TestResponse>(\"test-tool\"),\n );\n\n const mockResponse: TestResponse = {\n content: [{ type: \"text\" as const, text: \"data\" }],\n structuredContent: { data: \"test data\" },\n isError: false,\n meta: {},\n };\n\n OpenaiMock.callTool.mockResolvedValueOnce(mockResponse);\n\n const returnedValue = await act(async () => {\n return result.current.callToolAsync();\n });\n expectTypeOf<typeof mockResponse>(returnedValue);\n expect(returnedValue).toEqual(mockResponse);\n });\n});\n"]}
@@ -43,6 +43,13 @@ export function skybridge(options) {
43
43
  }
44
44
  return {
45
45
  base: "/assets",
46
+ // Fixes "Invalid hook call" on createStore by forcing a single
47
+ // copy of React. Under pnpm's isolated node_modules, zustand
48
+ // inside `skybridge` resolves React from skybridge's own
49
+ // dependencies while the host app loads its own copy
50
+ resolve: {
51
+ dedupe: ["react", "react-dom"],
52
+ },
46
53
  build: {
47
54
  outDir: "dist/assets",
48
55
  emptyOutDir: true,
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../src/web/plugin/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE1D,OAAO,EACL,qBAAqB,EAErB,iBAAiB,EACjB,aAAa,EACb,aAAa,GACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,IAAI,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAC3C,MAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAMlD,SAAS,iBAAiB,CAAC,YAAoB;IAC7C,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACpD,OAAO;QACL,4CAA4C;QAC5C,0BAA0B,UAAU,IAAI;QACxC,wCAAwC;QACxC,sCAAsC;KACvC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,SAAS,mBAAmB,CAAC,QAAgB;IAC3C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tC,CAAC;QAED,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE;YACtB,IAAI,gBAAgB,EAAE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;gBAC9D,IAAI,CAAC,IAAI,CACP,cAAc,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,gCAAgC,CAClE,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { isAbsolute, relative, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport {\n assertUniqueViewNames,\n type DiscoveredView,\n discoverViewsSync,\n scanViewsSync,\n writeViewsDts,\n} from \"./scan-views.js\";\nimport { transform as dataLlmTransform } from \"./transform-data-llm.js\";\nimport { hasDefaultExport } from \"./validate-view.js\";\n\nconst VIRTUAL_PREFIX = \"/_skybridge/view/\";\nconst VIRTUAL_MODULE_PREFIX = \"\\0skybridge:view:\";\n\nexport interface SkybridgePluginOptions {\n viewsDir?: string;\n}\n\nfunction buildVirtualEntry(viewFilePath: string): string {\n const normalized = viewFilePath.replace(/\\\\/g, \"/\");\n return [\n `import { mountView } from \"skybridge/web\";`,\n `import Component from \"${normalized}\";`,\n `import { createElement } from \"react\";`,\n `mountView(createElement(Component));`,\n ].join(\"\\n\");\n}\n\nfunction getViewEntryPattern(viewsDir: string): RegExp {\n const escaped = viewsDir.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(\n `${escaped}\\\\/(?:[^/]+\\\\.(?:jsx|tsx)|[^/]+\\\\/index\\\\.(?:tsx|jsx))(?:\\\\?.*)?$`,\n );\n}\n\nexport function skybridge(options?: SkybridgePluginOptions): Plugin {\n const rawViewsDir = options?.viewsDir ?? \"src/views\";\n let resolvedViewsDir: string;\n let projectRoot: string;\n let viewMap = new Map<string, DiscoveredView>();\n let viewEntryPattern: RegExp;\n\n return {\n name: \"skybridge\",\n enforce: \"pre\",\n // Read by `skybridge build` to resolve viewsDir before `tsc -b` runs.\n api: { viewsDir: rawViewsDir },\n\n config(config) {\n projectRoot = config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(projectRoot, rawViewsDir);\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n\n const views = discoverViewsSync(resolvedViewsDir);\n viewMap = new Map(views.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, views);\n\n const input: Record<string, string> = {};\n for (const view of views) {\n input[view.name] = `${VIRTUAL_PREFIX}${view.name}`;\n }\n\n return {\n base: \"/assets\",\n build: {\n outDir: \"dist/assets\",\n emptyOutDir: true,\n manifest: true,\n minify: true,\n cssCodeSplit: false,\n rollupOptions: {\n input,\n },\n },\n // Pre-bundle view deps at startup so the first tool invocation\n // doesn't hit Vite's on-demand re-optimization path (which sends\n // `full-reload` over HMR — in our iframe flow the parent host\n // can't honour a reload, and the view silently never mounts).\n optimizeDeps: {\n // Scan view files so transitive user deps (zod, tailwind, etc.)\n // get pre-bundled at startup.\n entries: [\n `${resolvedViewsDir}/*.{tsx,jsx}`,\n `${resolvedViewsDir}/*/index.{tsx,jsx}`,\n ],\n include: [\"react\", \"react-dom/client\", \"react/jsx-runtime\"],\n exclude: [\"skybridge/web\"],\n },\n experimental: {\n renderBuiltUrl: (filename) => {\n return {\n runtime: `window.skybridge.serverUrl + \"/assets/${filename}\"`,\n };\n },\n },\n };\n },\n\n resolveId(id) {\n if (id.startsWith(VIRTUAL_PREFIX)) {\n const name = id.slice(VIRTUAL_PREFIX.length);\n if (viewMap.has(name)) {\n return `${VIRTUAL_MODULE_PREFIX}${name}`;\n }\n }\n return null;\n },\n\n load(id) {\n if (id.startsWith(VIRTUAL_MODULE_PREFIX)) {\n const name = id.slice(VIRTUAL_MODULE_PREFIX.length);\n const view = viewMap.get(name);\n if (view) {\n return buildVirtualEntry(view.filePath);\n }\n }\n return null;\n },\n\n configureServer(server: ViteDevServer) {\n if (!resolvedViewsDir) {\n const root = server.config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(root, rawViewsDir);\n projectRoot = root;\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n }\n\n server.watcher.add(resolvedViewsDir);\n // Track which view files we've already warned about so a rescan\n // triggered by an unrelated edit doesn't re-emit the same warning.\n let knownInvalid = new Set<string>();\n const rescan = () => {\n try {\n // Surface broken view files. Without this, files lacking a\n // default export are silently dropped from the input and the\n // user has no idea why their widget never mounts.\n const { valid, invalid } = scanViewsSync(resolvedViewsDir);\n const nextInvalid = new Set(invalid.map((v) => v.filePath));\n\n for (const filePath of nextInvalid) {\n if (!knownInvalid.has(filePath)) {\n server.config.logger.warn(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" is missing a default export — it won't be served until fixed.`,\n );\n }\n }\n for (const filePath of knownInvalid) {\n if (!nextInvalid.has(filePath)) {\n server.config.logger.info(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" resolved.`,\n );\n }\n }\n knownInvalid = nextInvalid;\n\n assertUniqueViewNames(valid);\n viewMap = new Map(valid.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, valid);\n } catch (err) {\n // assertUniqueViewNames throws on duplicate view names. Catch so\n // chokidar's listener chain doesn't surface it as unhandled and\n // crash the dev server — previous viewMap stays active until\n // the user fixes the conflict.\n const message = err instanceof Error ? err.message : String(err);\n server.config.logger.error(\n `[skybridge] view rescan failed: ${message}`,\n );\n }\n };\n\n // Initial scan emits warnings for broken files that exist at startup.\n rescan();\n server.watcher.on(\"add\", rescan);\n server.watcher.on(\"change\", rescan);\n server.watcher.on(\"unlink\", rescan);\n },\n\n async transform(code, id) {\n if (viewEntryPattern?.test(id) && !hasDefaultExport(code, id)) {\n this.warn(\n `View file \"${id.split(\"/\").pop()}\" is missing a default export.`,\n );\n }\n\n return await dataLlmTransform(code, id);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../src/web/plugin/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE1D,OAAO,EACL,qBAAqB,EAErB,iBAAiB,EACjB,aAAa,EACb,aAAa,GACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,IAAI,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAC3C,MAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAMlD,SAAS,iBAAiB,CAAC,YAAoB;IAC7C,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACpD,OAAO;QACL,4CAA4C;QAC5C,0BAA0B,UAAU,IAAI;QACxC,wCAAwC;QACxC,sCAAsC;KACvC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED,SAAS,mBAAmB,CAAC,QAAgB;IAC3C,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;IAChE,OAAO,IAAI,MAAM,CACf,GAAG,OAAO,mEAAmE,CAC9E,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,OAAgC;IACxD,MAAM,WAAW,GAAG,OAAO,EAAE,QAAQ,IAAI,WAAW,CAAC;IACrD,IAAI,gBAAwB,CAAC;IAC7B,IAAI,WAAmB,CAAC;IACxB,IAAI,OAAO,GAAG,IAAI,GAAG,EAA0B,CAAC;IAChD,IAAI,gBAAwB,CAAC;IAE7B,OAAO;QACL,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,KAAK;QACd,s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MAAM,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { isAbsolute, relative, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport {\n assertUniqueViewNames,\n type DiscoveredView,\n discoverViewsSync,\n scanViewsSync,\n writeViewsDts,\n} from \"./scan-views.js\";\nimport { transform as dataLlmTransform } from \"./transform-data-llm.js\";\nimport { hasDefaultExport } from \"./validate-view.js\";\n\nconst VIRTUAL_PREFIX = \"/_skybridge/view/\";\nconst VIRTUAL_MODULE_PREFIX = \"\\0skybridge:view:\";\n\nexport interface SkybridgePluginOptions {\n viewsDir?: string;\n}\n\nfunction buildVirtualEntry(viewFilePath: string): string {\n const normalized = viewFilePath.replace(/\\\\/g, \"/\");\n return [\n `import { mountView } from \"skybridge/web\";`,\n `import Component from \"${normalized}\";`,\n `import { createElement } from \"react\";`,\n `mountView(createElement(Component));`,\n ].join(\"\\n\");\n}\n\nfunction getViewEntryPattern(viewsDir: string): RegExp {\n const escaped = viewsDir.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(\n `${escaped}\\\\/(?:[^/]+\\\\.(?:jsx|tsx)|[^/]+\\\\/index\\\\.(?:tsx|jsx))(?:\\\\?.*)?$`,\n );\n}\n\nexport function skybridge(options?: SkybridgePluginOptions): Plugin {\n const rawViewsDir = options?.viewsDir ?? \"src/views\";\n let resolvedViewsDir: string;\n let projectRoot: string;\n let viewMap = new Map<string, DiscoveredView>();\n let viewEntryPattern: RegExp;\n\n return {\n name: \"skybridge\",\n enforce: \"pre\",\n // Read by `skybridge build` to resolve viewsDir before `tsc -b` runs.\n api: { viewsDir: rawViewsDir },\n\n config(config) {\n projectRoot = config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(projectRoot, rawViewsDir);\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n\n const views = discoverViewsSync(resolvedViewsDir);\n viewMap = new Map(views.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, views);\n\n const input: Record<string, string> = {};\n for (const view of views) {\n input[view.name] = `${VIRTUAL_PREFIX}${view.name}`;\n }\n\n return {\n base: \"/assets\",\n // Fixes \"Invalid hook call\" on createStore by forcing a single\n // copy of React. Under pnpm's isolated node_modules, zustand\n // inside `skybridge` resolves React from skybridge's own\n // dependencies while the host app loads its own copy\n resolve: {\n dedupe: [\"react\", \"react-dom\"],\n },\n build: {\n outDir: \"dist/assets\",\n emptyOutDir: true,\n manifest: true,\n minify: true,\n cssCodeSplit: false,\n rollupOptions: {\n input,\n },\n },\n // Pre-bundle view deps at startup so the first tool invocation\n // doesn't hit Vite's on-demand re-optimization path (which sends\n // `full-reload` over HMR — in our iframe flow the parent host\n // can't honour a reload, and the view silently never mounts).\n optimizeDeps: {\n // Scan view files so transitive user deps (zod, tailwind, etc.)\n // get pre-bundled at startup.\n entries: [\n `${resolvedViewsDir}/*.{tsx,jsx}`,\n `${resolvedViewsDir}/*/index.{tsx,jsx}`,\n ],\n include: [\"react\", \"react-dom/client\", \"react/jsx-runtime\"],\n exclude: [\"skybridge/web\"],\n },\n experimental: {\n renderBuiltUrl: (filename) => {\n return {\n runtime: `window.skybridge.serverUrl + \"/assets/${filename}\"`,\n };\n },\n },\n };\n },\n\n resolveId(id) {\n if (id.startsWith(VIRTUAL_PREFIX)) {\n const name = id.slice(VIRTUAL_PREFIX.length);\n if (viewMap.has(name)) {\n return `${VIRTUAL_MODULE_PREFIX}${name}`;\n }\n }\n return null;\n },\n\n load(id) {\n if (id.startsWith(VIRTUAL_MODULE_PREFIX)) {\n const name = id.slice(VIRTUAL_MODULE_PREFIX.length);\n const view = viewMap.get(name);\n if (view) {\n return buildVirtualEntry(view.filePath);\n }\n }\n return null;\n },\n\n configureServer(server: ViteDevServer) {\n if (!resolvedViewsDir) {\n const root = server.config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(root, rawViewsDir);\n projectRoot = root;\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n }\n\n server.watcher.add(resolvedViewsDir);\n // Track which view files we've already warned about so a rescan\n // triggered by an unrelated edit doesn't re-emit the same warning.\n let knownInvalid = new Set<string>();\n const rescan = () => {\n try {\n // Surface broken view files. Without this, files lacking a\n // default export are silently dropped from the input and the\n // user has no idea why their widget never mounts.\n const { valid, invalid } = scanViewsSync(resolvedViewsDir);\n const nextInvalid = new Set(invalid.map((v) => v.filePath));\n\n for (const filePath of nextInvalid) {\n if (!knownInvalid.has(filePath)) {\n server.config.logger.warn(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" is missing a default export — it won't be served until fixed.`,\n );\n }\n }\n for (const filePath of knownInvalid) {\n if (!nextInvalid.has(filePath)) {\n server.config.logger.info(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" resolved.`,\n );\n }\n }\n knownInvalid = nextInvalid;\n\n assertUniqueViewNames(valid);\n viewMap = new Map(valid.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, valid);\n } catch (err) {\n // assertUniqueViewNames throws on duplicate view names. Catch so\n // chokidar's listener chain doesn't surface it as unhandled and\n // crash the dev server — previous viewMap stays active until\n // the user fixes the conflict.\n const message = err instanceof Error ? err.message : String(err);\n server.config.logger.error(\n `[skybridge] view rescan failed: ${message}`,\n );\n }\n };\n\n // Initial scan emits warnings for broken files that exist at startup.\n rescan();\n server.watcher.on(\"add\", rescan);\n server.watcher.on(\"change\", rescan);\n server.watcher.on(\"unlink\", rescan);\n },\n\n async transform(code, id) {\n if (viewEntryPattern?.test(id) && !hasDefaultExport(code, id)) {\n this.warn(\n `View file \"${id.split(\"/\").pop()}\" is missing a default export.`,\n );\n }\n\n return await dataLlmTransform(code, id);\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skybridge",
3
- "version": "0.36.3",
3
+ "version": "1.0.1",
4
4
  "description": "Skybridge is a framework for building ChatGPT and MCP Apps",
5
5
  "repository": {
6
6
  "type": "git",
@@ -41,7 +41,7 @@
41
41
  "license": "ISC",
42
42
  "peerDependencies": {
43
43
  "@modelcontextprotocol/sdk": ">=1.27.0",
44
- "@skybridge/devtools": ">=0.35.14 <1.0.0",
44
+ "@skybridge/devtools": "^1.0.0",
45
45
  "nodemon": ">=3.0.0",
46
46
  "react": ">=18.0.0",
47
47
  "react-dom": ">=18.0.0",