@ractive-ch/tab-mcp-client 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +118 -6
- package/cdn/connection-hgt931xk.min.js +12 -0
- package/cdn/{connection-jk28y9f6.min.js.map → connection-hgt931xk.min.js.map} +6 -5
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +3 -3
- package/cdn/ui-2nv84ry7.min.js +86 -0
- package/cdn/ui-2nv84ry7.min.js.map +14 -0
- package/{connection-h2ct4x47.js → connection-g6wk37yd.js} +291 -133
- package/connection-g6wk37yd.js.map +16 -0
- package/connection.d.ts +2 -5
- package/index.d.ts +1 -1
- package/index.js +37 -13
- package/index.js.map +3 -3
- package/internal.d.ts +2 -2
- package/mcp.d.ts +7 -6
- package/package.json +5 -1
- package/react.d.ts +5 -2
- package/react.js +3 -1
- package/react.js.map +3 -3
- package/serve.d.ts +46 -0
- package/tab-mcp.d.ts +17 -2
- package/tunnel.d.ts +74 -0
- package/tunnel.js +263 -0
- package/tunnel.js.map +10 -0
- package/types.d.ts +73 -9
- package/{ui-4qv8d1a3.js → ui-04mwfxm9.js} +4 -2
- package/ui-04mwfxm9.js.map +11 -0
- package/cdn/connection-jk28y9f6.min.js +0 -12
- package/cdn/ui-5zecjy7s.min.js +0 -86
- package/cdn/ui-5zecjy7s.min.js.map +0 -14
- package/connection-h2ct4x47.js.map +0 -15
- package/ui-4qv8d1a3.js.map +0 -11
package/README.md
CHANGED
|
@@ -6,9 +6,11 @@ Offer a web page's functions as [MCP](https://modelcontextprotocol.io) tools to
|
|
|
6
6
|
gets an address. The user adds that address to their AI app and types a pairing code
|
|
7
7
|
from the page; the AI app then calls the page's tools while the tab stays open. Nothing
|
|
8
8
|
is installed on the user's computer. With `webmcp: true` the library also registers the
|
|
9
|
-
tools with the browser's own [WebMCP](#webmcp), for agents in the browser.
|
|
9
|
+
tools with the browser's own [WebMCP](#webmcp), for agents in the browser. A site's own
|
|
10
|
+
assistant can call the same tools over a port, without a relay:
|
|
11
|
+
[Your own assistant on the page](#your-own-assistant-on-the-page).
|
|
10
12
|
|
|
11
|
-
**Status: 0.
|
|
13
|
+
**Status: 0.15.0.** Until 1.0, a new minor version can still change the API. Which AI apps
|
|
12
14
|
work is listed in [compatibility](https://github.com/ractive/tab-mcp/blob/main/docs/compatibility.md).
|
|
13
15
|
|
|
14
16
|
## You need a relay
|
|
@@ -30,6 +32,9 @@ docker run --rm -p 8080:8080 \
|
|
|
30
32
|
For production, see
|
|
31
33
|
[self-hosting](https://github.com/ractive/tab-mcp/blob/main/docs/self-hosting.md).
|
|
32
34
|
|
|
35
|
+
A page that offers its tools only to its own assistant (`serve`) or to agents in the
|
|
36
|
+
browser (`webmcp`) needs no relay: leave `relay` out.
|
|
37
|
+
|
|
33
38
|
## Install
|
|
34
39
|
|
|
35
40
|
```sh
|
|
@@ -40,7 +45,7 @@ Or without a bundler, from a CDN as an ES module:
|
|
|
40
45
|
|
|
41
46
|
```html
|
|
42
47
|
<script type="module">
|
|
43
|
-
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.
|
|
48
|
+
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.15.0/cdn/tab-mcp-client.min.js";
|
|
44
49
|
</script>
|
|
45
50
|
```
|
|
46
51
|
|
|
@@ -139,14 +144,16 @@ Chrome has WebMCP for sites in its
|
|
|
139
144
|
- The call resolves with what `execute` returned. A failure resolves too, as
|
|
140
145
|
`{ error: "<message>" }`, so that the agent can read it: invalid arguments (the same
|
|
141
146
|
message as for an AI app), "Don't allow" (`The user did not allow <tool> to run.`), a
|
|
142
|
-
|
|
147
|
+
question not answered (`The user did not answer whether <tool> may run.`), a tool that
|
|
148
|
+
is gone, an error thrown by `execute` (its message) and an MCP result with
|
|
143
149
|
`isError: true` (its text). A rejection would not help: Chrome 156 hands the agent
|
|
144
150
|
every rejection as a bare `UnknownError`, without its message. Two cases still
|
|
145
151
|
reject: a call the browser cancelled (`AbortError`), since its caller no longer waits
|
|
146
152
|
for an answer, and a call made when the library's lazily loaded part cannot be loaded
|
|
147
153
|
(a new deploy with other chunk names while the page stays open, the network, a
|
|
148
154
|
Content Security Policy); reloading the page fixes the latter.
|
|
149
|
-
`toolcallend` reports the outcome as for an AI app (`error`, `declined`, `
|
|
155
|
+
`toolcallend` reports the outcome as for an AI app (`error`, `declined`, `unanswered`,
|
|
156
|
+
`cancelled`).
|
|
150
157
|
- Only the native object is used, read through `Document.prototype`'s getter: an own
|
|
151
158
|
`document.modelContext` (a polyfill such as `@mcp-b/global`, or a page script) is
|
|
152
159
|
passed by, and with native WebMCP and the polyfill both present the tools go to the
|
|
@@ -165,6 +172,106 @@ Chrome has WebMCP for sites in its
|
|
|
165
172
|
does not offer them a second time to an AI app that is connected to the page and to
|
|
166
173
|
the extension.
|
|
167
174
|
|
|
175
|
+
### Your own assistant on the page
|
|
176
|
+
|
|
177
|
+
A site with its own AI assistant can let it use the page's tools without a relay,
|
|
178
|
+
pairing or an address. `mcp.serve(port, { client })` answers MCP requests on a message
|
|
179
|
+
port, and `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`) is a `fetch` for the
|
|
180
|
+
other end. The port carries the relay's `http.*` messages
|
|
181
|
+
([protocol](https://github.com/ractive/tab-mcp/blob/main/docs/protocol.md#the-tunnel-without-a-relay))
|
|
182
|
+
as plain objects, so anything that passes them on in order will do. A usual setup: the
|
|
183
|
+
assistant's chat runs in an iframe on the page, and its backend, which already holds a
|
|
184
|
+
WebSocket to that chat, runs the MCP client.
|
|
185
|
+
|
|
186
|
+
The page, without `relay`:
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { TabMcp } from "@ractive-ch/tab-mcp-client";
|
|
190
|
+
|
|
191
|
+
const mcp = new TabMcp({ server: { name: "shop", version: "1.0.0" } });
|
|
192
|
+
await mcp.registerTool({ name: "add_to_cart", description: "…", execute: addToCart });
|
|
193
|
+
|
|
194
|
+
const chat = document.querySelector<HTMLIFrameElement>("#chat")!;
|
|
195
|
+
let served: { close(): void } | undefined;
|
|
196
|
+
addEventListener("message", async (event) => {
|
|
197
|
+
// Only the chat's frame, on the chat's origin, gets a port.
|
|
198
|
+
if (event.origin !== "https://chat.example" || event.source !== chat.contentWindow) return;
|
|
199
|
+
if (event.data?.type !== "tools-wanted") return;
|
|
200
|
+
const { port1, port2 } = new MessageChannel();
|
|
201
|
+
served?.close(); // the chat asked again (it reloaded): the old port is dead
|
|
202
|
+
served = await mcp.serve(port1, { client: { id: "assistant", name: "Example assistant" } });
|
|
203
|
+
chat.contentWindow!.postMessage({ type: "tools-port" }, "https://chat.example", [port2]);
|
|
204
|
+
});
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
The chat in the iframe passes the messages on between the port and its WebSocket:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
parent.postMessage({ type: "tools-wanted" }, "https://shop.example");
|
|
211
|
+
addEventListener("message", (event) => {
|
|
212
|
+
if (event.origin !== "https://shop.example" || event.data?.type !== "tools-port") return;
|
|
213
|
+
const [port] = event.ports;
|
|
214
|
+
port.onmessage = (e) => socket.send(JSON.stringify({ tunnel: e.data }));
|
|
215
|
+
socket.addEventListener("message", (e) => {
|
|
216
|
+
const message = JSON.parse(e.data);
|
|
217
|
+
if (message.tunnel) port.postMessage(message.tunnel);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The backend (Bun, Node or anything with `fetch`'s `Request` and `Response`), here with
|
|
223
|
+
the MCP SDK's client:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
227
|
+
import { createTunnelFetch } from "@ractive-ch/tab-mcp-client/tunnel";
|
|
228
|
+
|
|
229
|
+
const tunnel = createTunnelFetch({
|
|
230
|
+
send: (message) => socket.send(JSON.stringify({ tunnel: message })),
|
|
231
|
+
});
|
|
232
|
+
socket.on("message", (data) => {
|
|
233
|
+
const message = JSON.parse(String(data));
|
|
234
|
+
if (message.tunnel) tunnel.receive(message.tunnel);
|
|
235
|
+
});
|
|
236
|
+
socket.on("close", () => tunnel.close());
|
|
237
|
+
|
|
238
|
+
// The page speaks MCP 2026-07-28 only: pin it, or the SDK starts with an older version.
|
|
239
|
+
const client = new Client(
|
|
240
|
+
{ name: "assistant", version: "1.0.0" },
|
|
241
|
+
{ versionNegotiation: { mode: { pin: "2026-07-28" } } },
|
|
242
|
+
);
|
|
243
|
+
// The URL is never fetched; only its path reaches the page.
|
|
244
|
+
await client.connect(
|
|
245
|
+
new StreamableHTTPClientTransport(new URL("https://tab.invalid/mcp"), { fetch: tunnel.fetch }),
|
|
246
|
+
);
|
|
247
|
+
const { tools } = await client.listTools();
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
- **A port is a key.** Whoever holds the other end calls the tools without pairing, and
|
|
251
|
+
the library cannot check who that is. Hand a port only to a frame whose origin you
|
|
252
|
+
checked, as above, and send it with that origin as the target, never `"*"`.
|
|
253
|
+
- Calls arrive with `client: { kind: "local", id, name }`, as given to `serve`. A `grant`
|
|
254
|
+
in a message is ignored, so the other end cannot pass for an AI app of the relay.
|
|
255
|
+
- A consequential tool still asks. The library's dialog names the caller
|
|
256
|
+
"Example assistant (this site's assistant)" and never offers "Always allow". A page
|
|
257
|
+
that lets its own assistant run such tools without asking answers `onConfirm` itself
|
|
258
|
+
for `request.client.kind === "local"`, and hands other calls to `mcp.confirmInPage`.
|
|
259
|
+
- `serve` resolves with `{ close() }`; `options.signal` does the same. Closing aborts the
|
|
260
|
+
calls in flight and tells the other end (`bye`), whose requests then end at once with
|
|
261
|
+
`-31003`. Close a serve whose port is dead, as above: its calls, listen streams and an
|
|
262
|
+
open confirmation would stay otherwise. `serve` may be called for several ports (each
|
|
263
|
+
port once at a time), and next to a relay connection and `webmcp: true`: one
|
|
264
|
+
registration reaches all three.
|
|
265
|
+
- `createTunnelFetch` answers a request that takes longer than `requestTimeoutMs`
|
|
266
|
+
(300 s by default; a `subscriptions/listen` stream is not limited) with the JSON-RPC
|
|
267
|
+
error `-31002`, and every request after `close()` with `-31003`, at HTTP 200 like the
|
|
268
|
+
relay: the MCP client reads an error, not a network failure. Only an aborted `signal`
|
|
269
|
+
rejects. Call `close()` when the channel to the page is gone; a closed tunnel stays
|
|
270
|
+
closed, so a new channel (or a new `serve`) gets a new `createTunnelFetch`.
|
|
271
|
+
- Without `relay`, `connect()`, `showConnectDialog()` and `newAddress()` reject with a
|
|
272
|
+
`TypeError`, nothing is read from or written to `localStorage`, `mcp.hasRelay` is
|
|
273
|
+
`false`, and React's `ConnectButton` renders nothing.
|
|
274
|
+
|
|
168
275
|
### Consequential tools
|
|
169
276
|
|
|
170
277
|
Mark tools that change or delete something with `consequentialHint: true`. The page then
|
|
@@ -212,6 +319,11 @@ const mcp = new TabMcp({
|
|
|
212
319
|
});
|
|
213
320
|
```
|
|
214
321
|
|
|
322
|
+
`onConfirm` returns `true` (run), `false` (the user refused) or `"unanswered"`: the user was
|
|
323
|
+
asked and did not answer, e.g. your question timed out. The AI app then reads "The user was
|
|
324
|
+
asked and did not answer." instead of "The user declined", and `toolcallend` has the
|
|
325
|
+
outcome `unanswered`. Any other value, and a throw, is a refusal.
|
|
326
|
+
|
|
215
327
|
`mcp.confirmInPage(request)` is the library's own dialog, for an `onConfirm` that
|
|
216
328
|
handles only some calls itself.
|
|
217
329
|
|
|
@@ -416,7 +528,7 @@ Instead of `showConnectDialog()`, use `connect()`, `disconnect()`, `newAddress()
|
|
|
416
528
|
`detail.sibling`, see above) and `error`. For an activity log, `toolcall`
|
|
417
529
|
and `toolcallend` report every call by an AI app (or, with `webmcp`, an agent in the
|
|
418
530
|
browser): its id, tool, arguments and caller as it starts, then its outcome (`ok`,
|
|
419
|
-
`error`, `declined` or `cancelled`), result and duration.
|
|
531
|
+
`error`, `declined`, `unanswered` or `cancelled`), result and duration.
|
|
420
532
|
|
|
421
533
|
```ts
|
|
422
534
|
mcp.addEventListener("toolcallend", (e) => {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var Rt=/^(?:\d{1,4}x\d{1,4}|any)$/;function vt(e){let{src:t,mimeType:n,sizes:o,theme:s}=e;if(typeof t!=="string")return;let i=/^https?:/i.test(t)&&t.length<=2048,r=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!i&&!r)return;let a={src:t};if(typeof n==="string"&&/^image\/[\w.+-]+$/i.test(n))a.mimeType=n.toLowerCase();let l=Array.isArray(o)?o.map((k)=>String(k).toLowerCase()).filter((k)=>Rt.test(k)):[];if(l.length>0)a.sizes=l;if(s==="light"||s==="dark")a.theme=s;return a}function _e(e){let t=[];for(let n of e){let o=typeof n==="object"&&n!==null?vt(n):void 0;if(o!==void 0)t.push(o);if(t.length===8)break}return t}function he(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return _e([...t??[]].filter((n)=>n.getAttribute("href")?.trim()).map((n)=>{let o={src:n.href};if(n.type)o.mimeType=n.type;let s=n.getAttribute("sizes");if(s)o.sizes=s.trim().split(/\s+/);let i=/prefers-color-scheme:\s*(light|dark)/i.exec(n.media);if(i)o.theme=i[1]?.toLowerCase();return o}))}catch{return[]}}function ie(e,t){let n=typeof e;if(n!==typeof t)return!1;let o=Array.isArray(e),s=Array.isArray(t);if(o!==s)return!1;if(o){let i=e.length;if(i!==t.length)return!1;for(let r=0;r<i;r++)if(!ie(e[r],t[r]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let l of i){if(!Object.prototype.hasOwnProperty.call(t,l))return!1;if(!ie(e[l],t[l]))return!1}return!0}return e===t}function D(e){return encodeURI(It(e)).replace(/#/g,"%23")}function It(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Tt=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,St=/^%[0-9A-Fa-f]{2}$/,Mt=/^[A-Za-z0-9._~-]$/;function _t(e){let t="";for(let n=0;n<e.length;){let o=e[n],s=e.slice(n,n+3);if(o==="%"&&St.test(s)){let r=String.fromCharCode(parseInt(s.slice(1),16));t+=Mt.test(r)?r:s.toUpperCase(),n+=3;continue}let i=String.fromCodePoint(e.codePointAt(n));t+=Tt.test(i)?i:encodeURIComponent(i),n+=i.length}return t}function $e(e,t){let n=new URL(e,t.href);return n.hash=n.hash?_t(n.hash.slice(1)):"",n}var Ct={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Et={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},At={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Ot=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function X(e,t=Object.create(null),n=Ot,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let r=$e(i,n);if(r.hash.length>1)t[r.href]=e;else if(r.hash="",o==="")n=r;else X(e,t,n)}}else if(e!==!0&&e!==!1)return t;let s=n.href+(o?"#"+o:"");if(t[s]!==void 0&&t[s]!==e)throw Error(`Duplicate schema URI "${s}".`);if(t[s]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s});if(e.$ref&&e.__absolute_ref__===void 0){let i=$e(e.$ref,n);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=$e(e.$recursiveRef,n);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=$e("#"+e.$anchor,n);t[i.href]=e}for(let i in e){if(At[i])continue;let r=`${o}/${D(i)}`,a=e[i];if(Array.isArray(a)){if(Ct[i]){let l=a.length;for(let k=0;k<l;k++)X(a[k],t,n,`${r}/${k}`)}}else if(Et[i])for(let l in a)X(a[l],t,n,`${r}/${D(l)}`);else X(a,t,n,r)}return t}var Pt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Nt=[0,31,28,31,30,31,30,31,31,30,31,30,31],jt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|([+-])(\d\d):(\d\d))?$/i,Ve=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,qt=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Ht=/^(?:(?:[^\x00-\x20\x7f"<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,zt=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Jt=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Ut=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Dt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Bt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Gt=/^("(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Vt=(e)=>{let t=e.match(Gt);if(!t)return!1;let n=t[1],o=t[2];if(!n||!o||n.length>64||o.length>253)return!1;if(n[0]!=='"'&&(n[0]==="."||n.endsWith(".")||n.includes("..")))return!1;if(o.startsWith("[")&&o.endsWith("]")){let s=o.slice(1,-1);if(/^ipv6:/i.test(s))return Fe.test(s.slice(5));return We.test(s)}return Ve.test(o)},We=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Fe=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Wt=(e)=>/^P(?:\d+W|(?:(?:\d+Y(?:\d+M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)(?:T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function G(e){return e.test.bind(e)}var Ce={date:Ke,time:Ye.bind(void 0,!0),"date-time":Yt,duration:Wt,uri:Qt,"uri-reference":G(qt),"uri-template":G(Ht),url:G(zt),email:Vt,hostname:G(Ve),ipv4:G(We),ipv6:G(Fe),regex:en,uuid:G(Jt),"json-pointer":G(Ut),"json-pointer-uri-fragment":G(Dt),"relative-json-pointer":G(Bt)};function Ft(e){return e%4===0&&(e%100!==0||e%400===0)}function Ke(e){let t=e.match(Pt);if(!t)return!1;let n=t[1],o=t[2],s=t[3];if(!n||!o||!s)return!1;let i=+n,r=+o,a=+s,l=r==2&&Ft(i)?29:Nt[r];return r>=1&&r<=12&&a>=1&&l!==void 0&&a<=l}function Ye(e,t){let n=t.match(jt);if(!n)return!1;let o=n[1],s=n[2],i=n[3];if(!o||!s||!i)return!1;let r=+o,a=+s,l=+i,k=n[5],b=n[6],_=+(n[7]??0),H=+(n[8]??0);if(r>23||a>59||l>60||_>23||H>59||e&&k===void 0)return!1;if(l<60)return!0;let N=b==="+"?1:b==="-"?-1:0;return(r*60+a-N*(_*60+H)+1440)%1440===1439}var Kt=/t|\s/i;function Yt(e){let[t,n,o]=e.split(Kt);return t!==void 0&&n!==void 0&&o===void 0&&Ke(t)&&Ye(!0,n)}var Xt=/\/|:/,Zt=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Qt(e){return Xt.test(e)&&Zt.test(e)}var Lt=/[^\\]\\Z/;function en(e){if(Lt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function Xe(e){let t=0,n=e.length,o=0,s;while(o<n)if(t++,s=e.charCodeAt(o++),s>=55296&&s<=56319&&o<n){if(s=e.charCodeAt(o),(s&64512)==56320)o++}return t}function ne(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ze(e){let t=Math.abs(e).toString().split("e"),n=t[0],o=t[1]??"0",s=n.indexOf("."),i=s===-1?0:n.length-s-1;return[BigInt(n.replace(".","")),Number(o)-i]}function tn(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[n,o]=Ze(e),[s,i]=Ze(t),r=o-i;if(r>=0)return n*10n**BigInt(r)%s===0n;return n%(s*10n**BigInt(-r))===0n}function P(e,t,n="2019-09",o=X(t),s=!0,i=null,r="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:r,keyword:"false",keywordLocation:r,error:"False boolean schema."}]};let k=typeof e,b;switch(k){case"boolean":case"number":case"string":b=k;break;case"object":if(e===null)b="null";else if(Array.isArray(e))b="array";else b="object";break;default:throw Error(`Instances of "${k}" type are not supported.`)}let{$ref:_,$recursiveRef:H,$recursiveAnchor:N,type:E,const:j,enum:S,required:A,not:p,anyOf:g,allOf:v,oneOf:T,if:I,then:C,else:d,format:x,properties:M,patternProperties:q,additionalProperties:se,unevaluatedProperties:z,minProperties:Y,maxProperties:B,propertyNames:Q,dependentRequired:L,dependentSchemas:He,dependencies:Re,prefixItems:ve,items:le,additionalItems:ze,unevaluatedItems:Je,contains:Ue,minContains:F,maxContains:Ie,minItems:Te,maxItems:Se,uniqueItems:xt,minimum:ee,maximum:te,exclusiveMinimum:fe,exclusiveMaximum:ce,multipleOf:Me,minLength:pe,maxLength:me,pattern:De,__absolute_ref__:ye,__absolute_recursive_ref__:kt}=t,f=[];if(N===!0&&i===null)i=t;if(H==="#"){let w=i===null?o[kt]:i,m=`${a}/$recursiveRef`,R=P(e,i===null?t:i,n,o,s,w,r,m,l);if(!R.valid)f.push({instanceLocation:r,keyword:"$recursiveRef",keywordLocation:m,error:"A subschema had errors."},...R.errors)}if(_!==void 0){let m=o[ye||_];if(m===void 0){let u=`Unresolved $ref "${_}".`;if(ye&&ye!==_)u+=` Absolute URI "${ye}".`;throw u+=`
|
|
2
|
+
Known schemas:
|
|
3
|
+
- ${Object.keys(o).join(`
|
|
4
|
+
- `)}`,Error(u)}let R=`${a}/$ref`,c=P(e,m,n,o,s,i,r,R,l);if(!c.valid)f.push({instanceLocation:r,keyword:"$ref",keywordLocation:R,error:"A subschema had errors."},...c.errors);if(n==="4"||n==="7")return{valid:f.length===0,errors:f}}if(Array.isArray(E)){let w=E.length,m=!1;for(let R=0;R<w;R++)if(b===E[R]||E[R]==="integer"&&b==="number"&&e%1===0&&e===e){m=!0;break}if(!m)f.push({instanceLocation:r,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${b}" is invalid. Expected "${E.join('", "')}".`})}else if(E==="integer"){if(b!=="number"||e%1||e!==e)f.push({instanceLocation:r,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${b}" is invalid. Expected "${E}".`})}else if(E!==void 0&&b!==E)f.push({instanceLocation:r,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${b}" is invalid. Expected "${E}".`});if(j!==void 0){if(b==="object"||b==="array"){if(!ie(e,j))f.push({instanceLocation:r,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(j)}.`})}else if(e!==j)f.push({instanceLocation:r,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(j)}.`})}if(S!==void 0){if(b==="object"||b==="array"){if(!S.some((w)=>ie(e,w)))f.push({instanceLocation:r,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})}else if(!S.some((w)=>e===w))f.push({instanceLocation:r,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})}if(p!==void 0){let w=`${a}/not`;if(P(e,p,n,o,s,i,r,w).valid)f.push({instanceLocation:r,keyword:"not",keywordLocation:w,error:'Instance matched "not" schema.'})}let ge=[];if(g!==void 0){let w=`${a}/anyOf`,m=f.length,R=!1;for(let[c,u]of g.entries()){let h=Object.create(l),y=P(e,u,n,o,s,N===!0?i:null,r,`${w}/${c}`,h);if(f.push(...y.errors),R=R||y.valid,y.valid)ge.push(h)}if(R)f.length=m;else f.splice(m,0,{instanceLocation:r,keyword:"anyOf",keywordLocation:w,error:"Instance does not match any subschemas."})}if(v!==void 0){let w=`${a}/allOf`,m=f.length,R=!0;for(let[c,u]of v.entries()){let h=Object.create(l),y=P(e,u,n,o,s,N===!0?i:null,r,`${w}/${c}`,h);if(f.push(...y.errors),R=R&&y.valid,y.valid)ge.push(h)}if(R)f.length=m;else f.splice(m,0,{instanceLocation:r,keyword:"allOf",keywordLocation:w,error:"Instance does not match every subschema."})}if(T!==void 0){let w=`${a}/oneOf`,m=f.length,R=T.filter((c,u)=>{let h=Object.create(l),y=P(e,c,n,o,s,N===!0?i:null,r,`${w}/${u}`,h);if(f.push(...y.errors),y.valid)ge.push(h);return y.valid}).length;if(R===1)f.length=m;else f.splice(m,0,{instanceLocation:r,keyword:"oneOf",keywordLocation:w,error:`Instance does not match exactly one subschema (${R} matches).`})}if(b==="object"||b==="array")Object.assign(l,...ge);if(I!==void 0){let w=`${a}/if`,m=Object.create(null);if(P(e,I,n,o,s,i,r,w,m).valid){if(Object.assign(l,m),C!==void 0){let c=P(e,C,n,o,s,i,r,`${a}/then`,l);if(!c.valid)f.push({instanceLocation:r,keyword:"if",keywordLocation:w,error:'Instance does not match "then" schema.'},...c.errors)}}else if(d!==void 0){let c=P(e,d,n,o,s,i,r,`${a}/else`,l);if(!c.valid)f.push({instanceLocation:r,keyword:"if",keywordLocation:w,error:'Instance does not match "else" schema.'},...c.errors)}}if(b==="object"){if(A!==void 0){for(let c of A)if(!ne(e,c))f.push({instanceLocation:r,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${c}".`})}let w=Object.keys(e);if(Y!==void 0&&w.length<Y)f.push({instanceLocation:r,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${Y} properties.`});if(B!==void 0&&w.length>B)f.push({instanceLocation:r,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${B} properties.`});if(Q!==void 0){let c=`${a}/propertyNames`;for(let u in e){let h=`${r}/${D(u)}`,y=P(u,Q,n,o,s,i,h,c);if(!y.valid)f.push({instanceLocation:r,keyword:"propertyNames",keywordLocation:c,error:`Property name "${u}" does not match schema.`},...y.errors)}}if(L!==void 0){let c=`${a}/dependantRequired`;for(let u in L)if(ne(e,u)){let h=L[u];for(let y of h)if(!ne(e,y))f.push({instanceLocation:r,keyword:"dependentRequired",keywordLocation:c,error:`Instance has "${u}" but does not have "${y}".`})}}if(He!==void 0)for(let[c,u]of Object.entries(He)){let h=`${a}/dependentSchemas`;if(ne(e,c)){let y=P(e,u,n,o,s,i,r,`${h}/${D(c)}`,l);if(!y.valid)f.push({instanceLocation:r,keyword:"dependentSchemas",keywordLocation:h,error:`Instance has "${c}" but does not match dependant schema.`},...y.errors)}}if(Re!==void 0){let c=`${a}/dependencies`;for(let u in Re)if(ne(e,u)){let h=Re[u];if(Array.isArray(h)){for(let y of h)if(!ne(e,y))f.push({instanceLocation:r,keyword:"dependencies",keywordLocation:c,error:`Instance has "${u}" but does not have "${y}".`})}else{let y=P(e,h,n,o,s,i,r,`${c}/${D(u)}`);if(!y.valid)f.push({instanceLocation:r,keyword:"dependencies",keywordLocation:c,error:`Instance has "${u}" but does not match dependant schema.`},...y.errors)}}}let m=Object.create(null),R=!1;if(M!==void 0){let c=`${a}/properties`;for(let[u,h]of Object.entries(M)){if(!ne(e,u))continue;let y=`${r}/${D(u)}`,J=P(e[u],h,n,o,s,i,y,`${c}/${D(u)}`);if(m[u]=!0,J.valid)l[u]=!0;else if(R=s,f.push({instanceLocation:r,keyword:"properties",keywordLocation:c,error:`Property "${u}" does not match schema.`},...J.errors),R)break}}if(!R&&q!==void 0){let c=`${a}/patternProperties`;for(let[u,h]of Object.entries(q)){let y=new RegExp(u,"u");for(let J in e){if(!y.test(J))continue;let Be=`${r}/${D(J)}`,Ge=P(e[J],h,n,o,s,i,Be,`${c}/${D(u)}`);if(m[J]=!0,Ge.valid)l[J]=!0;else R=s,f.push({instanceLocation:r,keyword:"patternProperties",keywordLocation:c,error:`Property "${J}" matches pattern "${u}" but does not match associated schema.`},...Ge.errors)}}}if(!R&&se!==void 0){let c=`${a}/additionalProperties`;for(let u in e){if(m[u])continue;let h=`${r}/${D(u)}`,y=P(e[u],se,n,o,s,i,h,c);if(y.valid)l[u]=!0;else R=s,f.push({instanceLocation:r,keyword:"additionalProperties",keywordLocation:c,error:`Property "${u}" does not match additional properties schema.`},...y.errors)}}else if(!R&&z!==void 0){let c=`${a}/unevaluatedProperties`;for(let u in e)if(!l[u]){let h=`${r}/${D(u)}`,y=P(e[u],z,n,o,s,i,h,c);if(y.valid)l[u]=!0;else f.push({instanceLocation:r,keyword:"unevaluatedProperties",keywordLocation:c,error:`Property "${u}" does not match unevaluated properties schema.`},...y.errors)}}}else if(b==="array"){if(Se!==void 0&&e.length>Se)f.push({instanceLocation:r,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Se}).`});if(Te!==void 0&&e.length<Te)f.push({instanceLocation:r,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Te}).`});let w=e.length,m=0,R=!1;if(ve!==void 0){let c=`${a}/prefixItems`,u=Math.min(ve.length,w);for(;m<u;m++){let h=P(e[m],ve[m],n,o,s,i,`${r}/${m}`,`${c}/${m}`);if(l[m]=!0,!h.valid){if(R=s,f.push({instanceLocation:r,keyword:"prefixItems",keywordLocation:c,error:"Items did not match schema."},...h.errors),R)break}}}if(le!==void 0){let c=`${a}/items`;if(Array.isArray(le)){let u=Math.min(le.length,w);for(;m<u;m++){let h=P(e[m],le[m],n,o,s,i,`${r}/${m}`,`${c}/${m}`);if(l[m]=!0,!h.valid){if(R=s,f.push({instanceLocation:r,keyword:"items",keywordLocation:c,error:"Items did not match schema."},...h.errors),R)break}}}else for(;m<w;m++){let u=P(e[m],le,n,o,s,i,`${r}/${m}`,c);if(l[m]=!0,!u.valid){if(R=s,f.push({instanceLocation:r,keyword:"items",keywordLocation:c,error:"Items did not match schema."},...u.errors),R)break}}if(!R&&ze!==void 0){let u=`${a}/additionalItems`;for(;m<w;m++){let h=P(e[m],ze,n,o,s,i,`${r}/${m}`,u);if(l[m]=!0,!h.valid)R=s,f.push({instanceLocation:r,keyword:"additionalItems",keywordLocation:u,error:"Items did not match additional items schema."},...h.errors)}}}if(Ue!==void 0)if(w===0&&F===void 0)f.push({instanceLocation:r,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(F!==void 0&&w<F)f.push({instanceLocation:r,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${w}) than minContains (${F}).`});else{let c=`${a}/contains`,u=f.length,h=0;for(let y=0;y<w;y++){let J=P(e[y],Ue,n,o,s,i,`${r}/${y}`,c);if(J.valid)l[y]=!0,h++;else f.push(...J.errors)}if(h>=(F||0))f.length=u;if(F===void 0&&h===0)f.splice(u,0,{instanceLocation:r,keyword:"contains",keywordLocation:c,error:"Array does not contain item matching schema."});else if(F!==void 0&&h<F)f.push({instanceLocation:r,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${F} items matching schema. Only ${h} items were found.`});else if(Ie!==void 0&&h>Ie)f.push({instanceLocation:r,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ie} items matching schema. ${h} items were found.`})}if(!R&&Je!==void 0){let c=`${a}/unevaluatedItems`;for(m;m<w;m++){if(l[m])continue;let u=P(e[m],Je,n,o,s,i,`${r}/${m}`,c);if(l[m]=!0,!u.valid)f.push({instanceLocation:r,keyword:"unevaluatedItems",keywordLocation:c,error:"Items did not match unevaluated items schema."},...u.errors)}}if(xt)for(let c=0;c<w;c++){let u=e[c],h=typeof u==="object"&&u!==null;for(let y=0;y<w;y++){if(c===y)continue;let J=e[y];if(u===J||h&&(typeof J==="object"&&J!==null)&&ie(u,J))f.push({instanceLocation:r,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${c} and ${y}.`}),c=Number.MAX_SAFE_INTEGER,y=Number.MAX_SAFE_INTEGER}}}else if(b==="number"){if(n==="4"){if(ee!==void 0&&(fe===!0&&e<=ee||e<ee))f.push({instanceLocation:r,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${fe?"or equal to ":""} ${ee}.`});if(te!==void 0&&(ce===!0&&e>=te||e>te))f.push({instanceLocation:r,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${ce?"or equal to ":""} ${te}.`})}else{if(ee!==void 0&&e<ee)f.push({instanceLocation:r,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${ee}.`});if(te!==void 0&&e>te)f.push({instanceLocation:r,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${te}.`});if(fe!==void 0&&e<=fe)f.push({instanceLocation:r,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${fe}.`});if(ce!==void 0&&e>=ce)f.push({instanceLocation:r,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ce}.`})}if(Me!==void 0){if(!tn(e,Me))f.push({instanceLocation:r,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Me}.`})}}else if(b==="string"){let w=pe===void 0&&me===void 0?0:Xe(e);if(pe!==void 0&&w<pe)f.push({instanceLocation:r,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${w} < ${pe}).`});if(me!==void 0&&w>me)f.push({instanceLocation:r,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${w} > ${me}).`});if(De!==void 0&&!new RegExp(De,"u").test(e))f.push({instanceLocation:r,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(x!==void 0&&Ce[x]&&!Ce[x](e))f.push({instanceLocation:r,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${x}".`})}return{valid:f.length===0,errors:f}}var Le="ch.ractive.tab-mcp/annotations",nn=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],rn=["destructiveHint","idempotentHint","openWorldHint"];function et(e){let t={};if(e.readOnlyHint===!0)t.readOnlyHint=!0,t.destructiveHint=!1;else if(e.readOnlyHint===!1)t.readOnlyHint=!1;if(e.consequentialHint===!0)t.destructiveHint=!0;if(e.untrustedContentHint===!0)t.openWorldHint=!0;for(let s of rn){let i=e[s];if(i!==void 0)t[s]=i}let n={};for(let s of nn){let i=e[s];if(i!==void 0)n[s]=i}let o={};if(Object.keys(t).length>0)o.annotations=t;if(Object.keys(n).length>0)o.meta=n;return o}function ae(e){return{content:[{type:"text",text:e}],isError:!0}}function Qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tt(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(Qe(e)&&Array.isArray(e.content))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return ae("The tool returned a value that is not JSON.");let n={content:[{type:"text",text:t}]};if(Qe(e))n.structuredContent=e;return n}function nt(e){let t=e instanceof Error?e.message:String(e);return ae(t||"The tool failed.")}var re="2026-07-28",Z="io.modelcontextprotocol/protocolVersion",be="io.modelcontextprotocol/clientCapabilities",rt="io.modelcontextprotocol/clientInfo",ot="io.modelcontextprotocol/serverInfo",Ee="io.modelcontextprotocol/subscriptionId",on=-32020,st=-32022,sn=0,it=new WeakMap;function Ae(e){let t=it.get(e);if(t!==void 0)return t;let n=e.inputSchema,o;try{o=X(n)}catch(i){let r=i instanceof Error?i.message:String(i);throw Error(r.split(`
|
|
5
|
+
`)[0])}for(let i of Object.values(o)){if(typeof i!=="object"||i.$ref===void 0)continue;let r=i.__absolute_ref__;if(o[r??i.$ref]===void 0)throw Error(`$ref ${JSON.stringify(i.$ref)} does not resolve`)}let s=(i)=>P(i,n,"2020-12",o,!1);return it.set(e,s),s}function at(e,t,n=""){let o=t instanceof Error?t.message:String(t);return TypeError(`registerTool: the inputSchema of ${e}: ${o}${n}`)}function an(e){let t=[];for(let n of e.list())try{Ae(n)}catch(o){e.remove(n),t.push(at(n.name,o,"; the tool was unregistered"))}return e.setCompiler((n)=>{try{Ae(n)}catch(o){throw at(n.name,o)}}),t}function dt(e){try{return structuredClone(e)}catch{return e}}var dn=new TextEncoder;function K(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Oe(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function U(e,t,n,o,s){let i={code:n,message:o};if(s!==void 0)i.data=s;return Oe(e,{jsonrpc:"2.0",id:t,error:i})}function V(e,t,n){return U(400,e,on,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}})}function de(e){return dn.encode(`event: message
|
|
6
|
+
data: ${JSON.stringify(e)}
|
|
7
|
+
|
|
8
|
+
`)}var ut={"content-type":"text/event-stream","cache-control":"no-cache"};function un(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function ln(e){if(!(e.startsWith("=?base64?")&&e.endsWith("?=")))return e;let t=e.slice(9,-2);if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return;try{let n=atob(t),o=Uint8Array.from(n,(s)=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{return}}function fn(e){if(!(Z in e))return{key:Z,problem:"missing"};if(!(be in e))return{key:be,problem:"missing"};if(typeof e[Z]!=="string")return{key:Z,problem:"expected a protocol version string"};if(!K(e[be]))return{key:be,problem:"expected an object"};let t=e[rt];if(t!==void 0&&!(K(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:rt,problem:"expected {name, version}"};return}function cn(e){let t=e.notifications;return K(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function pn(e,t){let n;try{n=Ae(e)(t)}catch(s){let i=s instanceof Error?s.message:String(s);return`The input schema of tool ${e.name} cannot be used: ${i}`}if(n.valid)return;let o=n.errors.filter((s)=>s.keyword!=="properties"&&s.keyword!=="$ref").map((s)=>`${s.instanceLocation} ${s.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${e.name}: ${o||"the arguments do not match the schema"}`}async function lt(e,t,n,o,s){let i={id:++sn,tool:t.name,arguments:dt(n),client:{...s}};if(t.title!==void 0)i.title=t.title;let r=Date.now();e.observe?.start(i);let a={outcome:"error",result:ae("Internal error")};try{a=await yn(e,t,n,o,s)}finally{e.observe?.end({id:i.id,tool:t.name,client:{...s},outcome:a.outcome,result:dt(a.result),durationMs:Date.now()-r})}return a}var mn="The user was asked and did not answer.";async function yn(e,t,n,o,s){let i=(l,k,b)=>({outcome:l,result:ae(k),stop:b}),r=pn(t,n);if(r!==void 0)return i("error",r,"invalid");if(t.annotations.consequentialHint===!0){let l={tool:{name:t.name,description:t.description},arguments:n,client:s,signal:o};if(t.title!==void 0)l.tool.title=t.title;let k=!1;try{k=await e.confirm(l)}catch{k=!1}if(k!==!0){if(o.aborted)return i("cancelled","The user declined","cancelled");return k==="unanswered"?i("unanswered",mn,"unanswered"):i("declined","The user declined","declined")}}if(o.aborted)return i("cancelled","Cancelled","cancelled");if(e.tools.get(t.name)!==t)return i("error","The tool is no longer available","gone");let a;try{let l=await t.execute(n,{signal:o,client:s});a={outcome:"ok",result:tt(l),returned:{value:l}}}catch(l){a={outcome:"error",result:nt(l)}}if(o.aborted)return{...a,outcome:"cancelled",stop:"cancelled"};if(a.result.isError===!0)a.outcome="error";return a}async function ft(e,t,n,o){let s=(a)=>({error:a}),i=`The tool ${t.name} is no longer available.`;if(e.tools.get(t.name)!==t)return s(i);if(!K(n))return s("The input must be an object.");let r=await lt(e,t,n,o instanceof AbortSignal?o:new AbortController().signal,{kind:"webmcp"});if(r.stop==="cancelled")throw new DOMException("Cancelled","AbortError");if(r.stop==="declined")return s(`The user did not allow ${t.name} to run.`);if(r.stop==="unanswered")return s(`The user did not answer whether ${t.name} may run.`);if(r.stop==="gone")return s(i);if(r.result.isError===!0)return s(gn(r.result)||"The tool failed.");return r.returned?.value}function gn(e){return e.content.map((t)=>K(t)&&t.type==="text"&&typeof t.text==="string"?t.text:"").filter((t)=>t!=="").join(`
|
|
9
|
+
`)}function we(e){let{tools:t,server:n}=e,o={name:n.name,version:n.version};if(n.title!==void 0)o.title=n.title;let s=_e(n.icons??[]),i=s.length>0?{...o,icons:s}:o,r=new Set,a=!1,l=(p={})=>({...p,[ot]:o});function k(p,g,v=l()){return{jsonrpc:"2.0",id:p,result:{...g,resultType:"complete",_meta:v}}}function b(){return t.list().map((p)=>{let g={name:p.name};if(p.title!==void 0)g.title=p.title;g.description=p.description,g.inputSchema=p.inputSchema;let{annotations:v,meta:T}=et(p.annotations);if(v!==void 0)g.annotations=v;if(T!==void 0)g._meta={[Le]:T};return g})}let _=(p)=>({kind:"invalid",message:p});async function H(p,g,v){let T=p.name;if(typeof T!=="string")return _("Invalid params: name must be a string");let I=t.get(T);if(I===void 0)return _(`Tool ${T} not found`);let C=p.arguments??{};if(!K(C))return _("Invalid params: arguments must be an object");return{kind:"result",result:(await lt(e,I,C,g,e.client(v))).result}}function N(p,g,v,T){let I=new ReadableStream({start:(C)=>{let d=(x)=>{if(v.aborted)return;let M;try{M=de(x)}catch{M=de(k(p,ae("The tool returned a result that is not JSON.")))}try{C.enqueue(M),C.close()}catch{}};H(g,v,T).then((x)=>d(x.kind==="invalid"?{jsonrpc:"2.0",id:p,error:{code:-32602,message:x.message}}:k(p,x.result)),()=>d({jsonrpc:"2.0",id:p,error:{code:-32603,message:"Internal error"}}))}});return new Response(I,{status:200,headers:ut})}function E(p,g,v){let T=cn(g),I={jsonrpc:"2.0",id:p,result:{resultType:"complete",_meta:l({[Ee]:p})}},C,d=new ReadableStream({start:(x)=>{if(x.enqueue(de({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:T,_meta:{[Ee]:p}}})),Object.keys(T).length===0){x.enqueue(de(I)),x.close();return}let M={id:p,send:(q)=>{try{x.enqueue(de(q))}catch{r.delete(M)}},end:()=>{r.delete(M);try{x.enqueue(de(I)),x.close()}catch{}}};C=M,r.add(M),v.addEventListener("abort",()=>{r.delete(M);try{x.close()}catch{}})},cancel:()=>{if(C!==void 0)r.delete(C)}});return new Response(d,{status:200,headers:ut})}function j(p,g){if(Array.isArray(g))return U(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!K(g)||g.jsonrpc!=="2.0")return U(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:v,id:T}=g;if(typeof v!=="string")return"result"in g||"error"in g?U(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):U(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let I=p.headers.get("mcp-protocol-version"),C=p.headers.get("mcp-method"),d=K(g.params)?g.params:{},x=K(d._meta)?d._meta:void 0,M=x!==void 0&&Z in x,q=typeof x?.[Z]==="string"?x[Z]:void 0,se=I!==null&&I>=re;if(T===void 0){if(q!==void 0&&I!==null&&I!==q)return V(null,I,`the notification envelope names protocol version ${q} but the MCP-Protocol-Version header names ${I}`);if((M||se)&&C!==null&&C!==v)return V(null,C,`the notification body names method ${v} but the Mcp-Method header names ${C}`);return"notification"}if(typeof T!=="string"&&typeof T!=="number")return U(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let z=T;if(!M||v==="initialize"&&(q===void 0||q<re)){if(v==="initialize"){if(se)return V(z,I,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let B=typeof d.protocolVersion==="string"?d.protocolVersion:void 0;return S(z,B)}if(se){let B=x===void 0?["_meta"]:[Z];return U(400,z,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${I}, but the request is missing the required per-request envelope key(s): ${B.join(", ")}`,{envelope:{missing:B}})}return S(z,I??void 0)}let Y=fn(x);if(Y!==void 0)return U(400,z,-32602,`Invalid _meta envelope for protocol revision ${re}: ${Y.key}: ${Y.problem}`,{envelope:Y});if(I!==null&&q!==void 0&&I!==q)return V(z,I,`the body envelope names protocol version ${q} but the MCP-Protocol-Version header names ${I}`);if(C!==null&&C!==v)return V(z,C,`the body names method ${v} but the Mcp-Method header names ${C}`);if(q!==re)return S(z,q);if(I===null)return V(z,"(missing)",`the body envelope names protocol version ${q} but the required MCP-Protocol-Version header is absent`);if(C===null)return V(z,"(missing)",`the body names method ${v} but the required Mcp-Method header is absent`);if(v==="tools/call"&&typeof d.name==="string"){let B=d.name,Q=p.headers.get("mcp-name");if(Q===null)return V(z,"(missing)",`the body carries params.name="${B}" but the required Mcp-Name header is absent`);let L=ln(Q);if(L===void 0)return V(z,Q,"the Mcp-Name header carries an invalid Base64 sentinel value");if(L!==B)return V(z,Q,`the body carries params.name="${B}" but the Mcp-Name header names "${L}"`)}return{id:z,method:v,params:d}}function S(p,g){return g===void 0?U(400,p,st,"Unsupported protocol version: the request did not name a protocol version",{supported:[re]}):U(400,p,st,`Unsupported protocol version: ${g}`,{supported:[re],requested:g})}async function A(p,g){if(p.method.toUpperCase()!=="POST")return U(405,null,-32000,"Method not allowed.");if(!un(p.headers.get("content-type")))return U(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let v;try{v=JSON.parse(g.body??await p.text())}catch{return U(400,null,-32700,"Parse error: the request body is not valid JSON")}let T=j(p,v);if(T instanceof Response)return T;if(T==="notification")return new Response(null,{status:202});let{id:I,method:C,params:d}=T;switch(C){case"server/discover":{let x={supportedVersions:[re],capabilities:{tools:{listChanged:!0}}};if(n.instructions!==void 0)x.instructions=n.instructions;return x.ttlMs=0,x.cacheScope="private",Oe(200,k(I,x,{[ot]:i}))}case"tools/list":return Oe(200,k(I,{tools:b(),ttlMs:0,cacheScope:"private"}));case"tools/call":return N(I,d,p.signal,g.grant);case"subscriptions/listen":return E(I,d,p.signal);default:return U(404,I,-32601,"Method not found")}}return{handle:(p,g)=>A(p,g).catch(()=>U(500,null,-32603,"Internal server error")),toolsChanged(){if(a)return;a=!0,queueMicrotask(()=>{a=!1;for(let p of[...r])p.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[Ee]:p.id}}})})},close(){for(let p of[...r])p.end()}}}var xe="tab-mcp.v1",hn=new Set(["start","used","locked","expired"]);function ue(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var O=(e)=>typeof e==="string";function ct(e){if(!ue(e)||!O(e.grantId)||!O(e.createdAt))return!1;let t=e.client;return ue(t)&&O(t.id)&&O(t.name)&&O(t.host)}function $n(e){if(!ue(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function bn(e){return ue(e)&&Object.values(e).every(O)}function pt(e){let t;try{t=JSON.parse(e)}catch{return}if(!ue(t))return;switch(t.type){case"session":return O(t.sessionId)&&O(t.address)&&O(t.origin)&&O(t.expiresAt)&&$n(t.limits)&&Array.isArray(t.grants)&&t.grants.every(ct)&&(t.appName===void 0||O(t.appName))&&(t.pairing===void 0||O(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:O(t.reason)?t.reason:""};case"http.request":return O(t.id)&&O(t.method)&&O(t.path)&&bn(t.headers)&&O(t.body)&&ue(t.grant)&&O(t.grant.grantId)&&O(t.grant.clientId)?t:void 0;case"http.cancel":return O(t.id)?t:void 0;case"pairing.code":{if(!O(t.code)||!O(t.expiresAt))return;let n={type:"pairing.code",code:t.code,expiresAt:t.expiresAt},o=t.reason;if(typeof o==="string"&&hn.has(o))n.reason=o;return n}case"grant.added":return ct(t.grant)?t:void 0;case"grant.removed":return O(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:O(t.reason)?t.reason:""}:void 0;case"identity.bound":return typeof t.round==="number"?{type:"identity.bound",round:t.round}:{type:"identity.bound"};case"error":return O(t.code)?t:void 0;default:return}}function ke(e){return{tools:e.registry,confirm:(t)=>e.confirm(t),observe:{start:(t)=>e.toolCallStarted(t),end:(t)=>e.toolCallEnded(t)}}}var wn=["content-type","cache-control"];function*je(e,t){let n=0;while(n<e.length){let o=Math.min(n+t,e.length),s=e.charCodeAt(o-1);if(o<e.length&&s>=55296&&s<=56319)o+=o-1>n?-1:1;yield e.slice(n,o),n=o}}function qe(e){let{handler:t,send:n}=e,o=new Map,s=!1;async function i(r){let a=new AbortController;o.get(r.id)?.abort(),o.set(r.id,a);let l=()=>!s&&o.get(r.id)===a&&!a.signal.aborted;try{let k=new Request(`https://tab.invalid${r.path}`,{method:r.method,headers:r.headers,signal:a.signal}),b=await t.handle(k,{grant:r.grant,body:r.body});if(!l()){await b.body?.cancel().catch(()=>{});return}let _={};for(let S of wn){let A=b.headers.get(S);if(A!==null)_[S]=A}let H=(_["content-type"]??"").startsWith("text/event-stream"),N=e.maxChunk();if(!H||b.body===null){let S=await b.text();if(!l())return;if(S.length<=N){n({type:"http.response",id:r.id,status:b.status,headers:_,body:S});return}n({type:"http.response.start",id:r.id,status:b.status,headers:_});for(let A of je(S,N)){if(!l())break;n({type:"http.response.chunk",id:r.id,data:A})}if(l())n({type:"http.response.end",id:r.id});return}n({type:"http.response.start",id:r.id,status:b.status,headers:_});let E=b.body.getReader(),j=new TextDecoder;a.signal.addEventListener("abort",()=>{E.cancel().catch(()=>{})});for(;;){let{done:S,value:A}=await E.read();if(S||!l())break;let p=j.decode(A,{stream:!0});for(let g of je(p,N))n({type:"http.response.chunk",id:r.id,data:g})}if(l())n({type:"http.response.end",id:r.id})}catch(k){if(l())e.error(k instanceof Error?k:Error(String(k))),n({type:"http.response",id:r.id,status:500,headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"Internal server error"}})})}finally{if(o.get(r.id)===a)o.delete(r.id)}}return{request(r){if(!s)i(r)},cancel(r){o.get(r)?.abort(),o.delete(r)},close(){if(s)return;s=!0;for(let r of o.values())r.abort();o.clear()}}}var xn=65536,mt=64,yt=128,Pe=new WeakSet,kn=0,W=(e)=>typeof e==="string";function Ne(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Rn(e,t,n){let o=n?.client;if(!Ne(o)||!W(o.id)||o.id===""||o.name!==void 0&&!W(o.name))throw TypeError("serve: client needs an id (and may have a name)");let s=n.maxChunk??xn;if(!Number.isInteger(s)||s<mt)throw TypeError(`serve: maxChunk must be a whole number of at least ${mt}`);if(typeof t?.postMessage!=="function"||!("onmessage"in t))throw TypeError("serve: the port needs postMessage and onmessage");if(Pe.has(t))throw new DOMException("serve: this port is served already; close that first","InvalidStateError");let i={kind:"local",id:o.id};if(o.name!==void 0&&o.name!=="")i.name=o.name;let r={grantId:`local:${++kn}`,clientId:o.id,scopes:["tools"]},a=!1,l=(j)=>{if(a)return!1;try{return t.postMessage(j),!0}catch{return!1}},k=we({...ke(e),server:{...e.server,icons:e.server.icons??he()},client:()=>({...i})}),b=e.registry.onChange(()=>k.toolsChanged()),_=qe({handler:k,send:l,maxChunk:()=>s,error:(j)=>e.error(j)}),H=(j,S)=>{let A={type:"error",code:"bad_message",message:j};if(W(S)&&S.length<=yt)A.id=S;l(A)},N=(j)=>{if(a)return;let S=j?.data;if(!Ne(S)||!W(S.type)){H("not a message");return}let A=S.id;switch(S.type){case"http.request":{let{method:p,path:g,headers:v,body:T}=S;if(!W(A)||A===""||A.length>yt||!W(p)||!W(g)||!g.startsWith("/")||!Ne(v)||!Object.values(v).every(W)||!W(T)){H("malformed http.request",A);return}_.request({type:"http.request",id:A,method:p,path:g,headers:v,body:T,grant:r});return}case"http.cancel":if(W(A))_.cancel(A);else H("malformed http.cancel");return;case"error":return;default:H(`unexpected ${S.type.slice(0,64)}`,A)}},E=()=>{if(a)return;if(n.signal?.removeEventListener("abort",E),b(),_.close(),k.close(),Pe.delete(t))l({type:"bye",reason:"closed"});if(a=!0,t.onmessage===N)t.onmessage=null};if(n.signal?.aborted===!0)return E(),{close:E};return n.signal?.addEventListener("abort",E),Pe.add(t),t.onmessage=N,{close:E}}function vn(e){let t="",n=0,o=0;for(let s of e){n=n<<8|s,o+=8;while(o>=5)o-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[n>>>o&31];n&=(1<<o)-1}if(o>0)t+="abcdefghijklmnopqrstuvwxyz234567"[n<<5-o&31];return t}async function In(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return vn(new Uint8Array(n))}catch{return}}function Tn(e,t){if(t===void 0)return e;let n=new URL(e);return n.searchParams.set("a",t),n.href}function ur(e,t,n,o){return ft(ke(e),t,n,o)}var Sn=15000,gt={1000:"closed",1008:"policy",1009:"too_large",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited",4009:"policy"},ht={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function oe(e,t){return Object.assign(Error(e),{reason:t})}function Mn(){let e=globalThis.document?.title;return typeof e==="string"?e.slice(0,300):""}function _n(e){try{let t=JSON.parse(e);if(typeof t!=="object"||t===null||typeof t.type!=="string")return;return typeof t.id==="string"?{type:t.type,id:t.id}:{type:t.type}}catch{return}}var Cn=new Set(["session","ping","bye","http.request","http.cancel","pairing.code","grant.added","grant.removed","identity.bound","error"]),$t=512,bt=6,wt=64,En=$t+bt*wt;function An(e){let t=Math.floor((e-$t)/bt);return t>=wt?t:void 0}var On=1e4,Pn=1000;function Nn(e){let t,n=Number.NEGATIVE_INFINITY,o;try{if(e!==void 0&&typeof BroadcastChannel==="function")t=new BroadcastChannel(e),t.onmessage=(s)=>{if(s.data?.type!=="claimed")return;n=Date.now(),o?.()}}catch{t=void 0}return{claimed(){try{t?.postMessage({type:"claimed"})}catch{}},heard(){if(Date.now()-n<=On)return Promise.resolve(!0);if(t===void 0)return Promise.resolve(!1);return new Promise((s)=>{let i=setTimeout(()=>s(!1),Pn);o=()=>{clearTimeout(i),s(!0)}})},close(){t?.close()}}}function lr(e,t,n,o=!1){let s=new WebSocket(t,xe),i="opening",r,a=65536,l,k=0,b=Nn(e.tabs),_,H,N,E=new Promise((d,x)=>{H=d,N=x});E.catch(()=>{});let j=setTimeout(()=>{v(oe("The relay did not answer in time.","network"))},Sn),S=we({...ke(e),server:{...e.server,icons:e.server.icons??he()},client:(d)=>e.clientFor(d)}),A=e.registry.onChange(()=>S.toolsChanged());function p(d){if(s.readyState!==WebSocket.OPEN)return!1;try{return s.send(JSON.stringify(d)),!0}catch{return!1}}function g(){if(k<=0)return;clearTimeout(l),l=setTimeout(()=>{r??="heartbeat",T(4003);try{s.close()}catch{}},k*2.5)}function v(d){if(i!=="opening")return;T(0),N(d);try{s.close()}catch{}}function T(d){if(i==="closed")return;let x=i==="ready";if(i="closed",clearTimeout(j),clearTimeout(l),A(),I.close(),S.close(),x){let M=r??gt[d]??(d===1006?"network":"closed");if(N(oe("The address was taken over again before its AI apps were disconnected.",M)),e.closed(M,d),M==="replaced"){b.heard().then((q)=>{b.close(),e.replaced({sibling:q})});return}}b.close()}let I=qe({handler:S,send:p,maxChunk:()=>a,error:(d)=>e.error(d)});function C(d){if(i==="opening"){if(d.type==="session"){let x=An(d.limits.maxMessageBytes);if(x===void 0){v(oe(`The relay's message limit (${d.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${En}.`,"policy"));return}a=x,i="ready",clearTimeout(j),k=d.limits.heartbeatMs,g(),b.claimed();let M=e.sessionStarted(d);if(o&&d.grants.length>0){_={left:new Set(d.grants.map((q)=>q.grantId)),session:M},p({type:"grants.revokeAll"});return}H(M)}else if(d.type==="error")v(oe(`The relay refused the connection: ${d.message||d.code}`,d.code==="rate_limited"?"rate_limited":"policy"));else if(d.type==="bye")v(oe(`The relay ended the connection: ${d.reason}`,ht[d.reason]??"closed"));return}if(i!=="ready")return;switch(d.type){case"ping":g(),p({type:"pong",t:d.t});return;case"http.request":I.request(d);return;case"http.cancel":I.cancel(d.id);return;case"pairing.code":e.pairingCode(d.reason===void 0?{code:d.code,expiresAt:d.expiresAt}:{code:d.code,expiresAt:d.expiresAt,reason:d.reason});return;case"grant.added":e.grantAdded(d.grant);return;case"grant.removed":if(e.grantRemoved(d.grantId),_?.left.delete(d.grantId),_?.left.size===0)H(_.session);return;case"identity.bound":e.identityResult(!0,d.round);return;case"bye":if(r=ht[d.reason]??"closed",r==="replaced")T(4005);return;case"error":if(d.code==="identity_refused"){e.identityResult(!1,typeof d.round==="number"?d.round:void 0,d.message);return}e.error(Error(`Relay error ${d.code}: ${d.message}`));return;case"session":return}}return s.addEventListener("open",()=>{if(s.protocol!==""&&s.protocol!==xe){v(oe(`The relay speaks ${s.protocol}, not ${xe}.`,"policy"));return}let d={type:"hello",library:e.library,page:{title:Mn()},secret:n};if(e.appName!==void 0)d.app={name:e.appName};if(o)d.revokeAll=!0;p(d)}),s.addEventListener("message",(d)=>{if(typeof d.data!=="string")return;let x=pt(d.data);if(x!==void 0){if(i==="ready")g();C(x);return}let M=_n(d.data);if(M?.id!==void 0)p(Cn.has(M.type)?{type:"error",code:"bad_message",message:`malformed ${M.type}`,id:M.id}:{type:"error",code:"unknown_type",message:`unknown type ${M.type}`,id:M.id})}),s.addEventListener("close",(d)=>{if(i==="opening"){T(d.code);let x=d.code===1006||d.code===1002;N(oe(x?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${d.code}${d.reason?`: ${d.reason}`:""}).`,gt[d.code]??(x?"network":"closed")));return}T(d.code)}),{ready:E,send:p,close(d){if(i==="closed")return;if(i==="opening"){v(new DOMException("The connection was cancelled","AbortError"));return}r=d,p({type:"bye",reason:"user"}),T(1000);try{s.close(1000,"bye")}catch{}}}}export{En as MIN_MESSAGE_BYTES,Pn as SIBLING_GRACE_MS,On as SIBLING_WINDOW_MS,In as addressIdOf,ur as callFromWebMcp,An as chunkSize,an as compileRegistry,lr as openConnection,je as pieces,Rn as servePort,Tn as withAddress};
|
|
10
|
+
|
|
11
|
+
//# debugId=0B4641130B5A2C4564756E2164756E21
|
|
12
|
+
//# sourceMappingURL=connection-hgt931xk.min.js.map
|