@ractive-ch/tab-mcp-client 0.2.0 → 0.4.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 +131 -11
- package/cdn/connection-by0y4k0a.min.js +10 -0
- package/cdn/{connection-5ehqkmw1.min.js.map → connection-by0y4k0a.min.js.map} +4 -4
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +4 -4
- package/cdn/ui-xh7shp5z.min.js +4 -0
- package/cdn/ui-xh7shp5z.min.js.map +10 -0
- package/{connection-ag7eyd36.js → connection-p2kxtegw.js} +23 -9
- package/{connection-ag7eyd36.js.map → connection-p2kxtegw.js.map} +4 -4
- package/index.d.ts +1 -1
- package/index.js +195 -7
- package/index.js.map +4 -4
- package/internal.d.ts +3 -0
- package/package.json +15 -2
- package/protocol.d.ts +16 -1
- package/react.d.ts +92 -0
- package/react.js +236 -0
- package/react.js.map +10 -0
- package/tab-mcp.d.ts +32 -2
- package/types.d.ts +67 -1
- package/{ui-wrm46a0a.js → ui-rtahm62h.js} +104 -21
- package/ui-rtahm62h.js.map +10 -0
- package/ui.d.ts +4 -2
- package/version.d.ts +1 -1
- package/cdn/connection-5ehqkmw1.min.js +0 -10
- package/cdn/ui-zmrhb8xg.min.js +0 -4
- package/cdn/ui-zmrhb8xg.min.js.map +0 -10
- package/ui-wrm46a0a.js.map +0 -10
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ relay. The page connects to the relay and gets an address. The user adds that ad
|
|
|
6
6
|
their AI app and types a pairing code from the page; the AI app then calls the page's
|
|
7
7
|
tools while the tab stays open. Nothing is installed on the user's computer.
|
|
8
8
|
|
|
9
|
-
**Status: 0.
|
|
9
|
+
**Status: 0.4.0.** Until 1.0, a new minor version can still change the API. Which AI apps
|
|
10
10
|
work is listed in [compatibility](https://github.com/ractive/tab-mcp/blob/main/docs/compatibility.md).
|
|
11
11
|
|
|
12
12
|
## You need a relay
|
|
@@ -22,7 +22,7 @@ docker run --rm -p 8080:8080 \
|
|
|
22
22
|
-e TAB_MCP_PUBLIC_URL=http://localhost:8080 \
|
|
23
23
|
-e TAB_MCP_ALLOWED_ORIGINS=http://localhost:3000 \
|
|
24
24
|
-e TAB_MCP_STORE=memory \
|
|
25
|
-
ractive/tab-mcp:0.
|
|
25
|
+
ractive/tab-mcp:0.3.0
|
|
26
26
|
```
|
|
27
27
|
|
|
28
28
|
For production, see
|
|
@@ -38,7 +38,7 @@ Or without a bundler, from a CDN as an ES module:
|
|
|
38
38
|
|
|
39
39
|
```html
|
|
40
40
|
<script type="module">
|
|
41
|
-
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.
|
|
41
|
+
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.4.0/cdn/tab-mcp-client.min.js";
|
|
42
42
|
</script>
|
|
43
43
|
```
|
|
44
44
|
|
|
@@ -108,6 +108,9 @@ const mcp = new TabMcp({
|
|
|
108
108
|
});
|
|
109
109
|
```
|
|
110
110
|
|
|
111
|
+
`mcp.confirmInPage(request)` is the library's own dialog, for an `onConfirm` that
|
|
112
|
+
handles only some calls itself.
|
|
113
|
+
|
|
111
114
|
### Connecting and pairing
|
|
112
115
|
|
|
113
116
|
1. The user clicks your button. `showConnectDialog()` connects (call it from the click
|
|
@@ -116,8 +119,15 @@ const mcp = new TabMcp({
|
|
|
116
119
|
2. The dialog shows the address and short instructions for Claude, ChatGPT and Claude
|
|
117
120
|
Code. The user adds the address to their AI app.
|
|
118
121
|
3. The AI app opens the relay's sign-in page in the browser. The dialog shows a 6-digit
|
|
119
|
-
code, which the user types there. The code changes every
|
|
120
|
-
|
|
122
|
+
code with a Copy button, which the user types or pastes there. The code changes every
|
|
123
|
+
2 minutes and after each use.
|
|
124
|
+
4. The dialog announces and lists the connected app with a Disconnect button, and shows
|
|
125
|
+
"Done" to close it.
|
|
126
|
+
|
|
127
|
+
Until an app connects, the dialog offers no prominent button under the code: only a small
|
|
128
|
+
"Close" at the bottom (and Escape). Closing it stops the code (`stopPairing()`); the page
|
|
129
|
+
stays connected and the address stays the same, so calling `showConnectDialog()` again
|
|
130
|
+
shows the same address with a new code.
|
|
121
131
|
|
|
122
132
|
The address stays the same across visits: the library keeps a secret per relay in
|
|
123
133
|
`localStorage`. "New address" in the dialog calls `newAddress()`, which disconnects every
|
|
@@ -126,16 +136,60 @@ sign-in page points users to it when someone else may be guessing codes. A page
|
|
|
126
136
|
own UI calls `newAddress()` from a click. Connected apps keep working after a reload once the page connects
|
|
127
137
|
again; while the page is closed, they get "the page is not open".
|
|
128
138
|
|
|
129
|
-
|
|
130
|
-
|
|
139
|
+
When the connection breaks (reason `network`, `heartbeat` or `shutdown`: a dropped
|
|
140
|
+
network, a phone pausing the tab in the background, a relay restart), the library
|
|
141
|
+
connects again by itself: after 5, 10, 20 and 40 seconds, then every 60 seconds, and at
|
|
142
|
+
once when the tab comes back to the front or the network returns. `reconnecting` (the
|
|
143
|
+
next attempt, its number and time) and the event `reconnecting` say so; `null` in the
|
|
144
|
+
event means it stopped, connected again or after `disconnect()`. Calling `connect()`
|
|
145
|
+
meanwhile tries at once. It never reconnects after `disconnect()`, a new address,
|
|
146
|
+
another tab taking over the address (`replaced`), an expired or idle session, or a
|
|
147
|
+
refusal by the relay, and an attempt the relay refuses stops it (an unreachable relay is
|
|
148
|
+
tried again). `reconnect: false` turns it off, `reconnect: { delaysMs: [...] }`
|
|
149
|
+
sets the waits (the last one repeats).
|
|
150
|
+
|
|
151
|
+
The library does not connect on page load by itself. A page that offers something like
|
|
152
|
+
"Keep AI access on" can call `connect({ resume: true })` on load.
|
|
153
|
+
|
|
154
|
+
### Identity binding (no code)
|
|
155
|
+
|
|
156
|
+
On a relay that pairs by `oidc` ([identity binding](https://github.com/ractive/tab-mcp/blob/main/docs/configuration.md#identity-binding)),
|
|
157
|
+
the user signs in to the AI app's connection with the account they use on your page,
|
|
158
|
+
and no code is shown. Your backend proves who is signed in: give the library a function
|
|
159
|
+
that fetches a short-lived tab assertion for the page's address.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
const mcp = new TabMcp({
|
|
163
|
+
relay: "https://relay.example.com",
|
|
164
|
+
server: { name: "Calculator", version: "1.0.0" },
|
|
165
|
+
identityAssertion: async ({ address }) => {
|
|
166
|
+
const res = await fetch("/api/tab-mcp-assertion", {
|
|
167
|
+
method: "POST",
|
|
168
|
+
headers: { "content-type": "application/json" },
|
|
169
|
+
body: JSON.stringify({ address }), // the assertion's aud
|
|
170
|
+
});
|
|
171
|
+
return res.ok ? (await res.json()).assertion : null; // null: nobody signed in
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// In your logout: the relay ends every AI connection of this page at once.
|
|
176
|
+
logoutButton.onclick = () => { mcp.signOut(); /* then your own logout */ };
|
|
177
|
+
// After a sign-in without a reload:
|
|
178
|
+
await mcp.refreshIdentity();
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The library asks the function after every connect. `identity` (`none`, `pending`,
|
|
182
|
+
`bound`, `refused`, with the reason in `identityMessage`) and the event
|
|
183
|
+
`identitychange` tell you whether the relay accepted it; without an answer within `identityTimeoutMs` (15 s) it goes back to `none`. An AI app signed in as someone else gets "This AI tool is logged in as someone other
|
|
184
|
+
than the page."
|
|
131
185
|
|
|
132
186
|
### Your own UI
|
|
133
187
|
|
|
134
188
|
Instead of `showConnectDialog()`, use `connect()`, `disconnect()`, `newAddress()`,
|
|
135
189
|
`startPairing()` and `stopPairing()` (codes come only while pairing is on),
|
|
136
|
-
`revoke(grantId)`, the properties `state`, `address`, `pairingCode`, `grants
|
|
137
|
-
`tools`, and the events `statechange`, `connected`, `disconnected`,
|
|
138
|
-
`grantschange`, `toolschange`, `replaced` and `error`. For an activity log, `toolcall`
|
|
190
|
+
`revoke(grantId)`, the properties `state`, `address`, `pairingCode`, `grants`,
|
|
191
|
+
`reconnecting` and `tools`, and the events `statechange`, `connected`, `disconnected`,
|
|
192
|
+
`pairingcode`, `grantschange`, `reconnecting`, `toolschange`, `replaced` and `error`. For an activity log, `toolcall`
|
|
139
193
|
and `toolcallend` report every call by an AI app: its id, tool, arguments and AI app as it
|
|
140
194
|
starts, then its outcome (`ok`, `error`, `declined` or `cancelled`), result and duration.
|
|
141
195
|
|
|
@@ -151,6 +205,71 @@ colours and sizes from `--tab-mcp-*` CSS custom properties (`--tab-mcp-font`,
|
|
|
151
205
|
`--tab-mcp-color`, `--tab-mcp-background`, `--tab-mcp-border`, `--tab-mcp-radius`, …)
|
|
152
206
|
and need no CSP exception.
|
|
153
207
|
|
|
208
|
+
## React
|
|
209
|
+
|
|
210
|
+
`@ractive-ch/tab-mcp-client/react` has bindings for single-page apps with React 18.3 or
|
|
211
|
+
19 (`react` is an optional peer dependency; pages without React install nothing more).
|
|
212
|
+
A provider makes one `TabMcp` for the tree, each component registers the tools it owns,
|
|
213
|
+
and a button opens the connect dialog:
|
|
214
|
+
|
|
215
|
+
```tsx
|
|
216
|
+
import { ConnectButton, TabMcpProvider, useTabMcpState, useTool } from "@ractive-ch/tab-mcp-client/react";
|
|
217
|
+
|
|
218
|
+
export function App() {
|
|
219
|
+
return (
|
|
220
|
+
<TabMcpProvider relay="https://relay.example" server={{ name: "todo", version: "1.0.0" }} appName="Todo">
|
|
221
|
+
<TodoList />
|
|
222
|
+
</TabMcpProvider>
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function TodoList() {
|
|
227
|
+
const todos = useTodos(); // your state
|
|
228
|
+
useTool({
|
|
229
|
+
name: "add_todo",
|
|
230
|
+
description: "Add a todo item",
|
|
231
|
+
inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
|
|
232
|
+
execute: ({ text }) => todos.add(String(text)),
|
|
233
|
+
});
|
|
234
|
+
const { state, grants } = useTabMcpState();
|
|
235
|
+
return <><ConnectButton /> {state === "connected" && `${grants.length} AI apps`}</>;
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
- `<TabMcpProvider {...options}>` takes the `TabMcp` options and makes the instance from
|
|
240
|
+
its first render. A changed `relay` or `server.name` makes a new one (with a warning);
|
|
241
|
+
other changes are ignored, except that `onConfirm` and `identityAssertion` are always
|
|
242
|
+
the latest ones, also when added or removed after the first render (without
|
|
243
|
+
`onConfirm`, the library's dialog asks). It disconnects its instance when it unmounts. `<TabMcpProvider
|
|
244
|
+
client={mcp}>` uses an instance of your own instead (and leaves it connected).
|
|
245
|
+
- `useTabMcp()` returns the instance, for everything the hooks do not cover
|
|
246
|
+
(`newAddress()`, `signOut()`, `refreshIdentity()`, `revoke()`, …).
|
|
247
|
+
- `useTabMcpState()` returns `{ state, address, session, grants, pairingCode, identity,
|
|
248
|
+
identityMessage, reconnecting, tools }` through `useSyncExternalStore`: the component
|
|
249
|
+
renders again only when one of them changed. On the server and during hydration it is
|
|
250
|
+
`disconnected`.
|
|
251
|
+
- `useTool(tool, deps?)` registers the tool while the component is mounted and removes it
|
|
252
|
+
on unmount. `execute` is always the latest closure, so it may use the component's
|
|
253
|
+
current props and state without registering again; the tool is registered again only
|
|
254
|
+
when its name, title, description, input schema or annotations change, or one of
|
|
255
|
+
`deps`. StrictMode's double mount registers it once at a time. A duplicate name or an
|
|
256
|
+
invalid tool is thrown from the component's render, for an error boundary. Tools that
|
|
257
|
+
read state right after another tool changed it should read it from a store (as the
|
|
258
|
+
example does), not from a render's props.
|
|
259
|
+
- `useToolCalls({ limit })` lists the AI app's tool calls since the component mounted,
|
|
260
|
+
newest first (default 20), each with its `end` (outcome, result, duration) once over.
|
|
261
|
+
- `<ConnectButton>` calls `showConnectDialog()`. Its label follows the state ("Connect
|
|
262
|
+
your AI app", "Connecting…", "Reconnecting…", "AI app connected"); `children` (a node,
|
|
263
|
+
or a function of the state) and the usual button props replace or style it, and
|
|
264
|
+
`data-state` (`disconnected`, `connecting`, `connected`, `reconnecting`) is there for
|
|
265
|
+
CSS. An `onClick` that calls `preventDefault()` keeps the dialog closed.
|
|
266
|
+
|
|
267
|
+
The module starts with `"use client"`, so React Server Components frameworks (Next.js's
|
|
268
|
+
app router) render the provider on the client; it never connects or touches storage on
|
|
269
|
+
the server. The CDN build does not include the React bindings: a page that loads tab-mcp
|
|
270
|
+
from a CDN uses the core API. [examples/react-todo](https://github.com/ractive/tab-mcp/tree/main/examples/react-todo)
|
|
271
|
+
is a complete todo app.
|
|
272
|
+
|
|
154
273
|
## Security
|
|
155
274
|
|
|
156
275
|
Connecting an AI app to a page means trusting that page, as with any MCP server. Keep
|
|
@@ -162,7 +281,8 @@ only to `localhost`). See
|
|
|
162
281
|
|
|
163
282
|
## More
|
|
164
283
|
|
|
165
|
-
- [
|
|
284
|
+
- [Live examples](https://ractive.ch/tab-mcp/)
|
|
285
|
+
- [Example: a React todo app](https://github.com/ractive/tab-mcp/tree/main/examples/react-todo)
|
|
166
286
|
- [Tab–relay protocol](https://github.com/ractive/tab-mcp/blob/main/docs/protocol.md)
|
|
167
287
|
- [Changelog](https://github.com/ractive/tab-mcp/blob/main/CHANGELOG.md)
|
|
168
288
|
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
function oe(e,t){let o=typeof e;if(o!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let s=e.length;if(s!==t.length)return!1;for(let i=0;i<s;i++)if(!oe(e[i],t[i]))return!1;return!0}if(o==="object"){if(!e||!t)return e===t;let s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(let n of s)if(!oe(e[n],t[n]))return!1;return!0}return e===t}function H(e){return encodeURI(nt(e))}function nt(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var ot={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},st={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},it={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!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},dt=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 F(e,t=Object.create(null),o=dt,s=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let d=e.$id||e.id;if(d){let n=new URL(d,o.href);if(n.hash.length>1)t[n.href]=e;else if(n.hash="",s==="")o=n;else F(e,t,o)}}else if(e!==!0&&e!==!1)return t;let i=o.href+(s?"#"+s:"");if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i});if(e.$ref&&e.__absolute_ref__===void 0){let d=new URL(e.$ref,o.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:d.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let d=new URL(e.$recursiveRef,o.href);d.hash=d.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:d.href})}if(e.$anchor){let d=new URL("#"+e.$anchor,o.href);t[d.href]=e}for(let d in e){if(it[d])continue;let n=`${s}/${H(d)}`,f=e[d];if(Array.isArray(f)){if(ot[d]){let I=f.length;for(let q=0;q<I;q++)F(f[q],t,o,`${n}/${q}`)}}else if(st[d])for(let I in f)F(f[I],t,o,`${n}/${H(I)}`);else F(f,t,o,n)}return t}var at=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ut=[0,31,28,31,30,31,30,31,31,30,31,30,31],lt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,ft=/^(?=.{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,ct=/^(?:[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,pt=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,yt=/^(?:(?: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,mt=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,gt=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ht=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,$t=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,bt=(e)=>{if(e[0]==='"')return!1;let[t,o,...s]=e.split("@");if(!t||!o||s.length!==0||t.length>64||o.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(o)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return o.split(".").every((i)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},wt=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,kt=/^((([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,Rt=(e)=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function V(e){return e.test.bind(e)}var Ie={date:Ce,time:Ne.bind(void 0,!1),"date-time":vt,duration:Rt,uri:_t,"uri-reference":V(ct),"uri-template":V(pt),url:V(yt),email:bt,hostname:V(ft),ipv4:V(wt),ipv6:V(kt),regex:Ot,uuid:V(mt),"json-pointer":V(gt),"json-pointer-uri-fragment":V(ht),"relative-json-pointer":V($t)};function xt(e){return e%4===0&&(e%100!==0||e%400===0)}function Ce(e){let t=e.match(at);if(!t)return!1;let o=+t[1],s=+t[2],i=+t[3];return s>=1&&s<=12&&i>=1&&i<=(s==2&&xt(o)?29:ut[s])}function Ne(e,t){let o=t.match(lt);if(!o)return!1;let s=+o[1],i=+o[2],d=+o[3],n=!!o[5];return(s<=23&&i<=59&&d<=59||s==23&&i==59&&d==60)&&(!e||n)}var It=/t|\s/i;function vt(e){let t=e.split(It);return t.length==2&&Ce(t[0])&&Ne(!0,t[1])}var Mt=/\/|:/,Tt=/^(?:[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 _t(e){return Mt.test(e)&&Tt.test(e)}var St=/[^\\]\\Z/;function Ot(e){if(St.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function qe(e){let t=0,o=e.length,s=0,i;while(s<o)if(t++,i=e.charCodeAt(s++),i>=55296&&i<=56319&&s<o){if(i=e.charCodeAt(s),(i&64512)==56320)s++}return t}function O(e,t,o="2019-09",s=F(t),i=!0,d=null,n="#",f="#",I=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:n,keyword:"false",keywordLocation:n,error:"False boolean schema."}]};let q=typeof e,T;switch(q){case"boolean":case"number":case"string":T=q;break;case"object":if(e===null)T="null";else if(Array.isArray(e))T="array";else T="object";break;default:throw Error(`Instances of "${q}" type are not supported.`)}let{$ref:J,$recursiveRef:ne,$recursiveAnchor:G,type:C,const:K,enum:E,required:Z,not:u,anyOf:m,allOf:x,oneOf:v,if:r,then:p,else:b,format:R,properties:M,patternProperties:_,additionalProperties:U,unevaluatedProperties:A,minProperties:B,maxProperties:P,propertyNames:j,dependentRequired:W,dependentSchemas:ae,dependencies:we,prefixItems:ke,items:ue,additionalItems:_e,unevaluatedItems:Se,contains:Oe,minContains:Y,maxContains:ce,minItems:Re,maxItems:xe,uniqueItems:tt,minimum:Q,maximum:L,exclusiveMinimum:le,exclusiveMaximum:fe,multipleOf:pe,minLength:ye,maxLength:me,pattern:Ee,__absolute_ref__:ge,__absolute_recursive_ref__:rt}=t,l=[];if(G===!0&&d===null)d=t;if(ne==="#"){let g=d===null?s[rt]:d,y=`${f}/$recursiveRef`,k=O(e,d===null?t:d,o,s,i,g,n,y,I);if(!k.valid)l.push({instanceLocation:n,keyword:"$recursiveRef",keywordLocation:y,error:"A subschema had errors."},...k.errors)}if(J!==void 0){let y=s[ge||J];if(y===void 0){let a=`Unresolved $ref "${J}".`;if(ge&&ge!==J)a+=` Absolute URI "${ge}".`;throw a+=`
|
|
2
|
+
Known schemas:
|
|
3
|
+
- ${Object.keys(s).join(`
|
|
4
|
+
- `)}`,Error(a)}let k=`${f}/$ref`,c=O(e,y,o,s,i,d,n,k,I);if(!c.valid)l.push({instanceLocation:n,keyword:"$ref",keywordLocation:k,error:"A subschema had errors."},...c.errors);if(o==="4"||o==="7")return{valid:l.length===0,errors:l}}if(Array.isArray(C)){let g=C.length,y=!1;for(let k=0;k<g;k++)if(T===C[k]||C[k]==="integer"&&T==="number"&&e%1===0&&e===e){y=!0;break}if(!y)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${f}/type`,error:`Instance type "${T}" is invalid. Expected "${C.join('", "')}".`})}else if(C==="integer"){if(T!=="number"||e%1||e!==e)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${f}/type`,error:`Instance type "${T}" is invalid. Expected "${C}".`})}else if(C!==void 0&&T!==C)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${f}/type`,error:`Instance type "${T}" is invalid. Expected "${C}".`});if(K!==void 0){if(T==="object"||T==="array"){if(!oe(e,K))l.push({instanceLocation:n,keyword:"const",keywordLocation:`${f}/const`,error:`Instance does not match ${JSON.stringify(K)}.`})}else if(e!==K)l.push({instanceLocation:n,keyword:"const",keywordLocation:`${f}/const`,error:`Instance does not match ${JSON.stringify(K)}.`})}if(E!==void 0){if(T==="object"||T==="array"){if(!E.some((g)=>oe(e,g)))l.push({instanceLocation:n,keyword:"enum",keywordLocation:`${f}/enum`,error:`Instance does not match any of ${JSON.stringify(E)}.`})}else if(!E.some((g)=>e===g))l.push({instanceLocation:n,keyword:"enum",keywordLocation:`${f}/enum`,error:`Instance does not match any of ${JSON.stringify(E)}.`})}if(u!==void 0){let g=`${f}/not`;if(O(e,u,o,s,i,d,n,g).valid)l.push({instanceLocation:n,keyword:"not",keywordLocation:g,error:'Instance matched "not" schema.'})}let he=[];if(m!==void 0){let g=`${f}/anyOf`,y=l.length,k=!1;for(let c=0;c<m.length;c++){let a=m[c],w=Object.create(I),h=O(e,a,o,s,i,G===!0?d:null,n,`${g}/${c}`,w);if(l.push(...h.errors),k=k||h.valid,h.valid)he.push(w)}if(k)l.length=y;else l.splice(y,0,{instanceLocation:n,keyword:"anyOf",keywordLocation:g,error:"Instance does not match any subschemas."})}if(x!==void 0){let g=`${f}/allOf`,y=l.length,k=!0;for(let c=0;c<x.length;c++){let a=x[c],w=Object.create(I),h=O(e,a,o,s,i,G===!0?d:null,n,`${g}/${c}`,w);if(l.push(...h.errors),k=k&&h.valid,h.valid)he.push(w)}if(k)l.length=y;else l.splice(y,0,{instanceLocation:n,keyword:"allOf",keywordLocation:g,error:"Instance does not match every subschema."})}if(v!==void 0){let g=`${f}/oneOf`,y=l.length,k=v.filter((c,a)=>{let w=Object.create(I),h=O(e,c,o,s,i,G===!0?d:null,n,`${g}/${a}`,w);if(l.push(...h.errors),h.valid)he.push(w);return h.valid}).length;if(k===1)l.length=y;else l.splice(y,0,{instanceLocation:n,keyword:"oneOf",keywordLocation:g,error:`Instance does not match exactly one subschema (${k} matches).`})}if(T==="object"||T==="array")Object.assign(I,...he);if(r!==void 0){let g=`${f}/if`;if(O(e,r,o,s,i,d,n,g,I).valid){if(p!==void 0){let k=O(e,p,o,s,i,d,n,`${f}/then`,I);if(!k.valid)l.push({instanceLocation:n,keyword:"if",keywordLocation:g,error:'Instance does not match "then" schema.'},...k.errors)}}else if(b!==void 0){let k=O(e,b,o,s,i,d,n,`${f}/else`,I);if(!k.valid)l.push({instanceLocation:n,keyword:"if",keywordLocation:g,error:'Instance does not match "else" schema.'},...k.errors)}}if(T==="object"){if(Z!==void 0){for(let c of Z)if(!(c in e))l.push({instanceLocation:n,keyword:"required",keywordLocation:`${f}/required`,error:`Instance does not have required property "${c}".`})}let g=Object.keys(e);if(B!==void 0&&g.length<B)l.push({instanceLocation:n,keyword:"minProperties",keywordLocation:`${f}/minProperties`,error:`Instance does not have at least ${B} properties.`});if(P!==void 0&&g.length>P)l.push({instanceLocation:n,keyword:"maxProperties",keywordLocation:`${f}/maxProperties`,error:`Instance does not have at least ${P} properties.`});if(j!==void 0){let c=`${f}/propertyNames`;for(let a in e){let w=`${n}/${H(a)}`,h=O(a,j,o,s,i,d,w,c);if(!h.valid)l.push({instanceLocation:n,keyword:"propertyNames",keywordLocation:c,error:`Property name "${a}" does not match schema.`},...h.errors)}}if(W!==void 0){let c=`${f}/dependantRequired`;for(let a in W)if(a in e){let w=W[a];for(let h of w)if(!(h in e))l.push({instanceLocation:n,keyword:"dependentRequired",keywordLocation:c,error:`Instance has "${a}" but does not have "${h}".`})}}if(ae!==void 0)for(let c in ae){let a=`${f}/dependentSchemas`;if(c in e){let w=O(e,ae[c],o,s,i,d,n,`${a}/${H(c)}`,I);if(!w.valid)l.push({instanceLocation:n,keyword:"dependentSchemas",keywordLocation:a,error:`Instance has "${c}" but does not match dependant schema.`},...w.errors)}}if(we!==void 0){let c=`${f}/dependencies`;for(let a in we)if(a in e){let w=we[a];if(Array.isArray(w)){for(let h of w)if(!(h in e))l.push({instanceLocation:n,keyword:"dependencies",keywordLocation:c,error:`Instance has "${a}" but does not have "${h}".`})}else{let h=O(e,w,o,s,i,d,n,`${c}/${H(a)}`);if(!h.valid)l.push({instanceLocation:n,keyword:"dependencies",keywordLocation:c,error:`Instance has "${a}" but does not match dependant schema.`},...h.errors)}}}let y=Object.create(null),k=!1;if(M!==void 0){let c=`${f}/properties`;for(let a in M){if(!(a in e))continue;let w=`${n}/${H(a)}`,h=O(e[a],M[a],o,s,i,d,w,`${c}/${H(a)}`);if(h.valid)I[a]=y[a]=!0;else if(k=i,l.push({instanceLocation:n,keyword:"properties",keywordLocation:c,error:`Property "${a}" does not match schema.`},...h.errors),k)break}}if(!k&&_!==void 0){let c=`${f}/patternProperties`;for(let a in _){let w=new RegExp(a,"u"),h=_[a];for(let z in e){if(!w.test(z))continue;let Pe=`${n}/${H(z)}`,Ae=O(e[z],h,o,s,i,d,Pe,`${c}/${H(a)}`);if(Ae.valid)I[z]=y[z]=!0;else k=i,l.push({instanceLocation:n,keyword:"patternProperties",keywordLocation:c,error:`Property "${z}" matches pattern "${a}" but does not match associated schema.`},...Ae.errors)}}}if(!k&&U!==void 0){let c=`${f}/additionalProperties`;for(let a in e){if(y[a])continue;let w=`${n}/${H(a)}`,h=O(e[a],U,o,s,i,d,w,c);if(h.valid)I[a]=!0;else k=i,l.push({instanceLocation:n,keyword:"additionalProperties",keywordLocation:c,error:`Property "${a}" does not match additional properties schema.`},...h.errors)}}else if(!k&&A!==void 0){let c=`${f}/unevaluatedProperties`;for(let a in e)if(!I[a]){let w=`${n}/${H(a)}`,h=O(e[a],A,o,s,i,d,w,c);if(h.valid)I[a]=!0;else l.push({instanceLocation:n,keyword:"unevaluatedProperties",keywordLocation:c,error:`Property "${a}" does not match unevaluated properties schema.`},...h.errors)}}}else if(T==="array"){if(xe!==void 0&&e.length>xe)l.push({instanceLocation:n,keyword:"maxItems",keywordLocation:`${f}/maxItems`,error:`Array has too many items (${e.length} > ${xe}).`});if(Re!==void 0&&e.length<Re)l.push({instanceLocation:n,keyword:"minItems",keywordLocation:`${f}/minItems`,error:`Array has too few items (${e.length} < ${Re}).`});let g=e.length,y=0,k=!1;if(ke!==void 0){let c=`${f}/prefixItems`,a=Math.min(ke.length,g);for(;y<a;y++){let w=O(e[y],ke[y],o,s,i,d,`${n}/${y}`,`${c}/${y}`);if(I[y]=!0,!w.valid){if(k=i,l.push({instanceLocation:n,keyword:"prefixItems",keywordLocation:c,error:"Items did not match schema."},...w.errors),k)break}}}if(ue!==void 0){let c=`${f}/items`;if(Array.isArray(ue)){let a=Math.min(ue.length,g);for(;y<a;y++){let w=O(e[y],ue[y],o,s,i,d,`${n}/${y}`,`${c}/${y}`);if(I[y]=!0,!w.valid){if(k=i,l.push({instanceLocation:n,keyword:"items",keywordLocation:c,error:"Items did not match schema."},...w.errors),k)break}}}else for(;y<g;y++){let a=O(e[y],ue,o,s,i,d,`${n}/${y}`,c);if(I[y]=!0,!a.valid){if(k=i,l.push({instanceLocation:n,keyword:"items",keywordLocation:c,error:"Items did not match schema."},...a.errors),k)break}}if(!k&&_e!==void 0){let a=`${f}/additionalItems`;for(;y<g;y++){let w=O(e[y],_e,o,s,i,d,`${n}/${y}`,a);if(I[y]=!0,!w.valid)k=i,l.push({instanceLocation:n,keyword:"additionalItems",keywordLocation:a,error:"Items did not match additional items schema."},...w.errors)}}}if(Oe!==void 0)if(g===0&&Y===void 0)l.push({instanceLocation:n,keyword:"contains",keywordLocation:`${f}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Y!==void 0&&g<Y)l.push({instanceLocation:n,keyword:"minContains",keywordLocation:`${f}/minContains`,error:`Array has less items (${g}) than minContains (${Y}).`});else{let c=`${f}/contains`,a=l.length,w=0;for(let h=0;h<g;h++){let z=O(e[h],Oe,o,s,i,d,`${n}/${h}`,c);if(z.valid)I[h]=!0,w++;else l.push(...z.errors)}if(w>=(Y||0))l.length=a;if(Y===void 0&&ce===void 0&&w===0)l.splice(a,0,{instanceLocation:n,keyword:"contains",keywordLocation:c,error:"Array does not contain item matching schema."});else if(Y!==void 0&&w<Y)l.push({instanceLocation:n,keyword:"minContains",keywordLocation:`${f}/minContains`,error:`Array must contain at least ${Y} items matching schema. Only ${w} items were found.`});else if(ce!==void 0&&w>ce)l.push({instanceLocation:n,keyword:"maxContains",keywordLocation:`${f}/maxContains`,error:`Array may contain at most ${ce} items matching schema. ${w} items were found.`})}if(!k&&Se!==void 0){let c=`${f}/unevaluatedItems`;for(y;y<g;y++){if(I[y])continue;let a=O(e[y],Se,o,s,i,d,`${n}/${y}`,c);if(I[y]=!0,!a.valid)l.push({instanceLocation:n,keyword:"unevaluatedItems",keywordLocation:c,error:"Items did not match unevaluated items schema."},...a.errors)}}if(tt)for(let c=0;c<g;c++){let a=e[c],w=typeof a==="object"&&a!==null;for(let h=0;h<g;h++){if(c===h)continue;let z=e[h];if(a===z||w&&(typeof z==="object"&&z!==null)&&oe(a,z))l.push({instanceLocation:n,keyword:"uniqueItems",keywordLocation:`${f}/uniqueItems`,error:`Duplicate items at indexes ${c} and ${h}.`}),c=Number.MAX_SAFE_INTEGER,h=Number.MAX_SAFE_INTEGER}}}else if(T==="number"){if(o==="4"){if(Q!==void 0&&(le===!0&&e<=Q||e<Q))l.push({instanceLocation:n,keyword:"minimum",keywordLocation:`${f}/minimum`,error:`${e} is less than ${le?"or equal to ":""} ${Q}.`});if(L!==void 0&&(fe===!0&&e>=L||e>L))l.push({instanceLocation:n,keyword:"maximum",keywordLocation:`${f}/maximum`,error:`${e} is greater than ${fe?"or equal to ":""} ${L}.`})}else{if(Q!==void 0&&e<Q)l.push({instanceLocation:n,keyword:"minimum",keywordLocation:`${f}/minimum`,error:`${e} is less than ${Q}.`});if(L!==void 0&&e>L)l.push({instanceLocation:n,keyword:"maximum",keywordLocation:`${f}/maximum`,error:`${e} is greater than ${L}.`});if(le!==void 0&&e<=le)l.push({instanceLocation:n,keyword:"exclusiveMinimum",keywordLocation:`${f}/exclusiveMinimum`,error:`${e} is less than ${le}.`});if(fe!==void 0&&e>=fe)l.push({instanceLocation:n,keyword:"exclusiveMaximum",keywordLocation:`${f}/exclusiveMaximum`,error:`${e} is greater than or equal to ${fe}.`})}if(pe!==void 0){let g=e%pe;if(Math.abs(0-g)>=0.00000011920929&&Math.abs(pe-g)>=0.00000011920929)l.push({instanceLocation:n,keyword:"multipleOf",keywordLocation:`${f}/multipleOf`,error:`${e} is not a multiple of ${pe}.`})}}else if(T==="string"){let g=ye===void 0&&me===void 0?0:qe(e);if(ye!==void 0&&g<ye)l.push({instanceLocation:n,keyword:"minLength",keywordLocation:`${f}/minLength`,error:`String is too short (${g} < ${ye}).`});if(me!==void 0&&g>me)l.push({instanceLocation:n,keyword:"maxLength",keywordLocation:`${f}/maxLength`,error:`String is too long (${g} > ${me}).`});if(Ee!==void 0&&!new RegExp(Ee,"u").test(e))l.push({instanceLocation:n,keyword:"pattern",keywordLocation:`${f}/pattern`,error:"String does not match pattern."});if(R!==void 0&&Ie[R]&&!Ie[R](e))l.push({instanceLocation:n,keyword:"format",keywordLocation:`${f}/format`,error:`String does not match format "${R}".`})}return{valid:l.length===0,errors:l}}class ve{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",o=!0){this.schema=e,this.draft=t,this.shortCircuit=o,this.lookup=F(e)}validate(e){return O(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};F(e,this.lookup)}}var ze="ch.ractive.tab-mcp/annotations",Et=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],Pt=["destructiveHint","idempotentHint","openWorldHint"];function He(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 i of Pt){let d=e[i];if(d!==void 0)t[i]=d}let o={};for(let i of Et){let d=e[i];if(d!==void 0)o[i]=d}let s={};if(Object.keys(t).length>0)s.annotations=t;if(Object.keys(o).length>0)s.meta=o;return s}function ee(e){return{content:[{type:"text",text:e}],isError:!0}}function je(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Je(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(je(e)&&Array.isArray(e.content))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return ee("The tool returned a value that is not JSON.");let o={content:[{type:"text",text:t}]};if(je(e))o.structuredContent=e;return o}function Ue(e){let t=e instanceof Error?e.message:String(e);return ee(t||"The tool failed.")}var te="2026-07-28",X="io.modelcontextprotocol/protocolVersion",$e="io.modelcontextprotocol/clientCapabilities",Be="io.modelcontextprotocol/clientInfo",At="io.modelcontextprotocol/serverInfo",Me="io.modelcontextprotocol/subscriptionId",Ct=-32020,Ve=-32022,Nt=0;function De(e){try{return structuredClone(e)}catch{return e}}var qt=new TextEncoder;function re(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Te(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function N(e,t,o,s,i){let d={code:o,message:s};if(i!==void 0)d.data=i;return Te(e,{jsonrpc:"2.0",id:t,error:d})}function D(e,t,o){return N(400,e,Ct,`Bad Request: the request headers and body disagree: ${o}`,{mismatch:{header:t,body:o}})}function se(e){return qt.encode(`event: message
|
|
5
|
+
data: ${JSON.stringify(e)}
|
|
6
|
+
|
|
7
|
+
`)}var Ge={"content-type":"text/event-stream","cache-control":"no-cache"};function jt(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function zt(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 o=atob(t),s=Uint8Array.from(o,(i)=>i.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(s)}catch{return}}function Ht(e){if(!(X in e))return{key:X,problem:"missing"};if(!($e in e))return{key:$e,problem:"missing"};if(typeof e[X]!=="string")return{key:X,problem:"expected a protocol version string"};if(!re(e[$e]))return{key:$e,problem:"expected an object"};let t=e[Be];if(t!==void 0&&!(re(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:Be,problem:"expected {name, version}"};return}function Jt(e){let t=e.notifications;return re(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function Ke(e){let{tools:t,server:o}=e,s={name:o.name,version:o.version};if(o.title!==void 0)s.title=o.title;let i=new WeakMap,d=new Set,n=!1,f=(u={})=>({...u,[At]:s});function I(u,m){return{jsonrpc:"2.0",id:u,result:{...m,resultType:"complete",_meta:f()}}}function q(u,m){let x=i.get(u);if(x===void 0)x=new ve(u.inputSchema,"2020-12",!1),i.set(u,x);let v=x.validate(m);if(v.valid)return;let r=v.errors.filter((p)=>p.keyword!=="properties"&&p.keyword!=="$ref").map((p)=>`${p.instanceLocation} ${p.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${u.name}: ${r||"the arguments do not match the schema"}`}function T(){return t.list().map((u)=>{let m={name:u.name};if(u.title!==void 0)m.title=u.title;m.description=u.description,m.inputSchema=u.inputSchema;let{annotations:x,meta:v}=He(u.annotations);if(x!==void 0)m.annotations=x;if(v!==void 0)m._meta={[ze]:v};return m})}async function J(u,m,x){let v=u.name;if(typeof v!=="string")return{invalid:"Invalid params: name must be a string"};let r=t.get(v);if(r===void 0)return{invalid:`Tool ${v} not found`};let p=u.arguments??{};if(!re(p))return{invalid:"Invalid params: arguments must be an object"};let b=e.client(x),R={id:++Nt,tool:r.name,arguments:De(p),client:{...b}};if(r.title!==void 0)R.title=r.title;let M=Date.now();e.observe?.start(R);let[_,U]=await ne(r,p,m,b);return e.observe?.end({id:R.id,tool:r.name,client:{...b},outcome:_,result:De(U),durationMs:Date.now()-M}),U}async function ne(u,m,x,v){let r=q(u,m);if(r!==void 0)return["error",ee(r)];if(u.annotations.consequentialHint===!0){let b={tool:{name:u.name,description:u.description},arguments:m,client:v,signal:x};if(u.title!==void 0)b.tool.title=u.title;let R=!1;try{R=await e.confirm(b)}catch{R=!1}if(!R)return[x.aborted?"cancelled":"declined",ee("The user declined")]}if(x.aborted)return["cancelled",ee("Cancelled")];let p;try{p=Je(await u.execute(m,{signal:x,client:v}))}catch(b){p=Ue(b)}if(x.aborted)return["cancelled",p];return[p.isError===!0?"error":"ok",p]}function G(u,m,x,v){let r=new ReadableStream({start:(p)=>{let b=(R)=>{if(x.aborted)return;let M;try{M=se(R)}catch{M=se(I(u,ee("The tool returned a result that is not JSON.")))}try{p.enqueue(M),p.close()}catch{}};J(m,x,v).then((R)=>b(typeof R.invalid==="string"?{jsonrpc:"2.0",id:u,error:{code:-32602,message:R.invalid}}:I(u,R)),()=>b({jsonrpc:"2.0",id:u,error:{code:-32603,message:"Internal error"}}))}});return new Response(r,{status:200,headers:Ge})}function C(u,m,x){let v=Jt(m),r={jsonrpc:"2.0",id:u,result:{resultType:"complete",_meta:f({[Me]:u})}},p,b=new ReadableStream({start:(R)=>{if(R.enqueue(se({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:v,_meta:{[Me]:u}}})),Object.keys(v).length===0){R.enqueue(se(r)),R.close();return}let M={id:u,send:(_)=>{try{R.enqueue(se(_))}catch{d.delete(M)}},end:()=>{d.delete(M);try{R.enqueue(se(r)),R.close()}catch{}}};p=M,d.add(M),x.addEventListener("abort",()=>{d.delete(M);try{R.close()}catch{}})},cancel:()=>{if(p!==void 0)d.delete(p)}});return new Response(b,{status:200,headers:Ge})}function K(u,m){if(Array.isArray(m))return N(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!re(m)||m.jsonrpc!=="2.0")return N(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:x,id:v}=m;if(typeof x!=="string")return"result"in m||"error"in m?N(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):N(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let r=u.headers.get("mcp-protocol-version"),p=u.headers.get("mcp-method"),b=re(m.params)?m.params:{},R=re(b._meta)?b._meta:void 0,M=R!==void 0&&X in R,_=typeof R?.[X]==="string"?R[X]:void 0,U=r!==null&&r>=te;if(v===void 0){if(_!==void 0&&r!==null&&r!==_)return D(null,r,`the notification envelope names protocol version ${_} but the MCP-Protocol-Version header names ${r}`);if((M||U)&&p!==null&&p!==x)return D(null,p,`the notification body names method ${x} but the Mcp-Method header names ${p}`);return"notification"}if(typeof v!=="string"&&typeof v!=="number")return N(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let A=v;if(!M||x==="initialize"&&(_===void 0||_<te)){if(x==="initialize"){if(U)return D(A,r,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let P=typeof b.protocolVersion==="string"?b.protocolVersion:void 0;return E(A,P)}if(U){let P=R===void 0?["_meta"]:[X];return N(400,A,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${r}, but the request is missing the required per-request envelope key(s): ${P.join(", ")}`,{envelope:{missing:P}})}return E(A,r??void 0)}let B=Ht(R);if(B!==void 0)return N(400,A,-32602,`Invalid _meta envelope for protocol revision ${te}: ${B.key}: ${B.problem}`,{envelope:B});if(r!==null&&_!==void 0&&r!==_)return D(A,r,`the body envelope names protocol version ${_} but the MCP-Protocol-Version header names ${r}`);if(p!==null&&p!==x)return D(A,p,`the body names method ${x} but the Mcp-Method header names ${p}`);if(_!==te)return E(A,_);if(r===null)return D(A,"(missing)",`the body envelope names protocol version ${_} but the required MCP-Protocol-Version header is absent`);if(p===null)return D(A,"(missing)",`the body names method ${x} but the required Mcp-Method header is absent`);if(x==="tools/call"&&typeof b.name==="string"){let P=b.name,j=u.headers.get("mcp-name");if(j===null)return D(A,"(missing)",`the body carries params.name="${P}" but the required Mcp-Name header is absent`);let W=zt(j);if(W===void 0)return D(A,j,"the Mcp-Name header carries an invalid Base64 sentinel value");if(W!==P)return D(A,j,`the body carries params.name="${P}" but the Mcp-Name header names "${W}"`)}return{id:A,method:x,params:b}}function E(u,m){return m===void 0?N(400,u,Ve,"Unsupported protocol version: the request did not name a protocol version",{supported:[te]}):N(400,u,Ve,`Unsupported protocol version: ${m}`,{supported:[te],requested:m})}async function Z(u,m){if(u.method.toUpperCase()!=="POST")return N(405,null,-32000,"Method not allowed.");if(!jt(u.headers.get("content-type")))return N(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let x;try{x=JSON.parse(m.body??await u.text())}catch{return N(400,null,-32700,"Parse error: the request body is not valid JSON")}let v=K(u,x);if(v instanceof Response)return v;if(v==="notification")return new Response(null,{status:202});let{id:r,method:p,params:b}=v;switch(p){case"server/discover":{let R={supportedVersions:[te],capabilities:{tools:{listChanged:!0}}};if(o.instructions!==void 0)R.instructions=o.instructions;return R.ttlMs=0,R.cacheScope="private",Te(200,I(r,R))}case"tools/list":return Te(200,I(r,{tools:T(),ttlMs:0,cacheScope:"private"}));case"tools/call":return G(r,b,u.signal,m.grant);case"subscriptions/listen":return C(r,b,u.signal);default:return N(404,r,-32601,"Method not found")}}return{handle:(u,m)=>Z(u,m).catch(()=>N(500,null,-32603,"Internal server error")),toolsChanged(){if(n)return;n=!0,queueMicrotask(()=>{n=!1;for(let u of[...d])u.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[Me]:u.id}}})})},close(){for(let u of[...d])u.end()}}}var be="tab-mcp.v1";function ie(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var S=(e)=>typeof e==="string";function We(e){if(!ie(e)||!S(e.grantId)||!S(e.createdAt))return!1;let t=e.client;return ie(t)&&S(t.id)&&S(t.name)&&S(t.host)}function Ut(e){if(!ie(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function Bt(e){return ie(e)&&Object.values(e).every(S)}function Ye(e){let t;try{t=JSON.parse(e)}catch{return}if(!ie(t))return;switch(t.type){case"session":return S(t.sessionId)&&S(t.address)&&S(t.origin)&&S(t.expiresAt)&&Ut(t.limits)&&Array.isArray(t.grants)&&t.grants.every(We)&&(t.appName===void 0||S(t.appName))&&(t.pairing===void 0||S(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:S(t.reason)?t.reason:""};case"http.request":return S(t.id)&&S(t.method)&&S(t.path)&&Bt(t.headers)&&S(t.body)&&ie(t.grant)&&S(t.grant.grantId)&&S(t.grant.clientId)?t:void 0;case"http.cancel":return S(t.id)?t:void 0;case"pairing.code":return S(t.code)&&S(t.expiresAt)?t:void 0;case"grant.added":return We(t.grant)?t:void 0;case"grant.removed":return S(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:S(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 S(t.code)?t:void 0;default:return}}var Vt=15000,Fe={1000:"closed",1008:"policy",1009:"too_large",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited"},Ze={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function de(e,t){return Object.assign(Error(e),{reason:t})}var Dt=["content-type","cache-control"];function Gt(){let e=globalThis.document?.title;return typeof e==="string"?e.slice(0,300):""}function Kt(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 Wt=new Set(["session","ping","bye","http.request","http.cancel","pairing.code","grant.added","grant.removed","identity.bound","error"]),Qe=512,Le=6,et=64,Yt=Qe+Le*et;function Ft(e){let t=Math.floor((e-Qe)/Le);return t>=et?t:void 0}function*Xe(e,t){let o=0;while(o<e.length){let s=Math.min(o+t,e.length),i=e.charCodeAt(s-1);if(s<e.length&&i>=55296&&i<=56319)s+=s-1>o?-1:1;yield e.slice(o,s),o=s}}function $r(e,t,o){let s=new WebSocket(t,be),i=new Map,d="opening",n,f=65536,I,q=0,T,J,ne=new Promise((r,p)=>{T=r,J=p});ne.catch(()=>{});let G=setTimeout(()=>{u(de("The relay did not answer in time.","network"))},Vt),C=Ke({tools:e.registry,server:e.server,confirm:(r)=>e.confirm(r),client:(r)=>e.clientFor(r),observe:{start:(r)=>e.toolCallStarted(r),end:(r)=>e.toolCallEnded(r)}}),K=e.registry.onChange(()=>C.toolsChanged());function E(r){if(s.readyState!==WebSocket.OPEN)return!1;try{return s.send(JSON.stringify(r)),!0}catch{return!1}}function Z(){if(q<=0)return;clearTimeout(I),I=setTimeout(()=>{n??="heartbeat",m(4003);try{s.close()}catch{}},q*2.5)}function u(r){if(d!=="opening")return;m(0),J(r);try{s.close()}catch{}}function m(r){if(d==="closed")return;let p=d==="ready";d="closed",clearTimeout(G),clearTimeout(I),K();for(let b of i.values())b.abort();if(i.clear(),C.close(),p){let b=n??Fe[r]??(r===1006?"network":"closed");e.closed(b,r)}}async function x(r){let p=new AbortController;i.set(r.id,p);let b=()=>d==="ready"&&i.get(r.id)===p&&!p.signal.aborted;try{let R=new Request(`https://tab.invalid${r.path}`,{method:r.method,headers:r.headers,signal:p.signal}),M=await C.handle(R,{grant:r.grant,body:r.body});if(!b()){await M.body?.cancel().catch(()=>{});return}let _={};for(let P of Dt){let j=M.headers.get(P);if(j!==null)_[P]=j}if(!(_["content-type"]??"").startsWith("text/event-stream")||M.body===null){let P=await M.text();if(!b())return;if(P.length<=f){E({type:"http.response",id:r.id,status:M.status,headers:_,body:P});return}E({type:"http.response.start",id:r.id,status:M.status,headers:_});for(let j of Xe(P,f)){if(!b())break;E({type:"http.response.chunk",id:r.id,data:j})}if(b())E({type:"http.response.end",id:r.id});return}E({type:"http.response.start",id:r.id,status:M.status,headers:_});let A=M.body.getReader(),B=new TextDecoder;p.signal.addEventListener("abort",()=>{A.cancel().catch(()=>{})});for(;;){let{done:P,value:j}=await A.read();if(P||!b())break;let W=B.decode(j,{stream:!0});for(let ae of Xe(W,f))E({type:"http.response.chunk",id:r.id,data:ae})}if(b())E({type:"http.response.end",id:r.id})}catch(R){if(b())e.error(R instanceof Error?R:Error(String(R))),E({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(i.get(r.id)===p)i.delete(r.id)}}function v(r){if(d==="opening"){if(r.type==="session"){let p=Ft(r.limits.maxMessageBytes);if(p===void 0){u(de(`The relay's message limit (${r.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${Yt}.`,"policy"));return}f=p,d="ready",clearTimeout(G),q=r.limits.heartbeatMs,Z(),T(e.sessionStarted(r))}else if(r.type==="error")u(de(`The relay refused the connection: ${r.message||r.code}`,r.code==="rate_limited"?"rate_limited":"policy"));else if(r.type==="bye")u(de(`The relay ended the connection: ${r.reason}`,Ze[r.reason]??"closed"));return}if(d!=="ready")return;switch(r.type){case"ping":Z(),E({type:"pong",t:r.t});return;case"http.request":x(r);return;case"http.cancel":i.get(r.id)?.abort(),i.delete(r.id);return;case"pairing.code":e.pairingCode({code:r.code,expiresAt:r.expiresAt});return;case"grant.added":e.grantAdded(r.grant);return;case"grant.removed":e.grantRemoved(r.grantId);return;case"identity.bound":e.identityResult(!0,r.round);return;case"bye":if(n=Ze[r.reason]??"closed",n==="replaced")e.replaced();return;case"error":if(r.code==="identity_refused"){e.identityResult(!1,typeof r.round==="number"?r.round:void 0,r.message);return}e.error(Error(`Relay error ${r.code}: ${r.message}`));return;case"session":return}}return s.addEventListener("open",()=>{if(s.protocol!==""&&s.protocol!==be){u(de(`The relay speaks ${s.protocol}, not ${be}.`,"policy"));return}let r={type:"hello",library:e.library,page:{title:Gt()},secret:o};if(e.appName!==void 0)r.app={name:e.appName};E(r)}),s.addEventListener("message",(r)=>{if(typeof r.data!=="string")return;let p=Ye(r.data);if(p!==void 0){if(d==="ready")Z();v(p);return}let b=Kt(r.data);if(b?.id!==void 0)E(Wt.has(b.type)?{type:"error",code:"bad_message",message:`malformed ${b.type}`,id:b.id}:{type:"error",code:"unknown_type",message:`unknown type ${b.type}`,id:b.id})}),s.addEventListener("close",(r)=>{if(d==="opening"){m(r.code);let p=r.code===1006||r.code===1002;J(de(p?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${r.code}${r.reason?`: ${r.reason}`:""}).`,Fe[r.code]??(p?"network":"closed")));return}m(r.code)}),{ready:ne,send:E,close(r){if(d==="closed")return;if(d==="opening"){u(new DOMException("The connection was cancelled","AbortError"));return}n=r,E({type:"bye",reason:"user"}),m(1000);try{s.close(1000,"bye")}catch{}}}}export{$r as openConnection};
|
|
8
|
+
|
|
9
|
+
//# debugId=E7A8964C77CC552E64756E2164756E21
|
|
10
|
+
//# sourceMappingURL=connection-by0y4k0a.min.js.map
|