lurqrun 0.1.6 → 0.1.8
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 +311 -139
- package/dist/auditHandler-VWCXSDVO.js +24 -0
- package/dist/autopilotInit-Q62MX5M6.js +178 -0
- package/dist/bin/lurq.js +3255 -23319
- package/dist/browserAuth-J7APSD4P.js +96 -0
- package/dist/cache-AEAKCV4I.js +12 -0
- package/dist/check-2JTQDQA6.js +2613 -0
- package/dist/check-PQSQ2MMA.js +192 -0
- package/dist/checkUpgrade-5YW77OBL.js +24 -0
- package/dist/chunk-2GAYNIHG.js +40 -0
- package/dist/chunk-2O6Z37IT.js +423 -0
- package/dist/chunk-2WD4QAH4.js +116 -0
- package/dist/chunk-3676XOBU.js +2235 -0
- package/dist/chunk-3D2MPGOQ.js +181 -0
- package/dist/chunk-3GHJR7XR.js +2049 -0
- package/dist/chunk-4ESO33J6.js +34 -0
- package/dist/chunk-4JHDSVIN.js +1229 -0
- package/dist/chunk-4KCPOMG6.js +68 -0
- package/dist/chunk-53SG6XWA.js +141 -0
- package/dist/chunk-5ABNDB3I.js +37 -0
- package/dist/chunk-5ALIJFDA.js +114 -0
- package/dist/chunk-63MUJNZL.js +318 -0
- package/dist/chunk-64ZF7KO4.js +1571 -0
- package/dist/chunk-6DM6UQFD.js +318 -0
- package/dist/chunk-6EQ3ARXA.js +304 -0
- package/dist/chunk-6L67QMCP.js +92 -0
- package/dist/chunk-72Y2FDVS.js +172 -0
- package/dist/chunk-A3TYI2TF.js +288 -0
- package/dist/chunk-B2UUYRBX.js +536 -0
- package/dist/chunk-BJT2LHAR.js +320 -0
- package/dist/chunk-BM3LF5T6.js +132 -0
- package/dist/chunk-BN3NM47Q.js +214 -0
- package/dist/chunk-BUALU27S.js +123 -0
- package/dist/chunk-C6GLE626.js +160 -0
- package/dist/chunk-D3K6IZVR.js +12845 -0
- package/dist/chunk-D3VTZS7V.js +222 -0
- package/dist/chunk-DM37MTOO.js +636 -0
- package/dist/chunk-DONTW3NE.js +171 -0
- package/dist/chunk-DSROTZ3Z.js +38 -0
- package/dist/chunk-ELGCAM7P.js +184 -0
- package/dist/chunk-EQCXENKZ.js +130 -0
- package/dist/chunk-EYAKM6YN.js +96 -0
- package/dist/chunk-FDFPMBCA.js +112 -0
- package/dist/chunk-FVYFV5HA.js +154 -0
- package/dist/chunk-GE37NVLN.js +15 -0
- package/dist/chunk-GM5Y555O.js +143 -0
- package/dist/chunk-GRJXQBQZ.js +793 -0
- package/dist/chunk-HWFX4BC4.js +177 -0
- package/dist/chunk-I3M2KJXB.js +56 -0
- package/dist/chunk-IFNONGRQ.js +603 -0
- package/dist/chunk-J3U2CPSK.js +136 -0
- package/dist/chunk-J6XQ7OPZ.js +74 -0
- package/dist/chunk-KMV4Y6R3.js +127 -0
- package/dist/chunk-KP5ZDDPE.js +340 -0
- package/dist/chunk-KYKSZ3XZ.js +202 -0
- package/dist/chunk-LEGPB7DO.js +81 -0
- package/dist/chunk-LUAKDHLZ.js +40 -0
- package/dist/chunk-MHUEVBVO.js +35 -0
- package/dist/chunk-MYGSLK44.js +37 -0
- package/dist/chunk-NEZNAPPN.js +41 -0
- package/dist/chunk-NPVN2THM.js +197 -0
- package/dist/chunk-NYZU5NCW.js +23 -0
- package/dist/chunk-O4KHCV6I.js +320 -0
- package/dist/chunk-ONDVTXUO.js +240 -0
- package/dist/chunk-OTJFHESY.js +176 -0
- package/dist/chunk-P6MIKSPY.js +243 -0
- package/dist/chunk-Q5VPF4WI.js +26 -0
- package/dist/chunk-QCRBX3LV.js +165 -0
- package/dist/chunk-QKGYDMWB.js +7409 -0
- package/dist/chunk-QSL6QN5X.js +115 -0
- package/dist/chunk-QUIMQ7YL.js +73 -0
- package/dist/chunk-RG3YLU6E.js +49 -0
- package/dist/chunk-SHCEBP3J.js +107 -0
- package/dist/chunk-SHZFOSXC.js +462 -0
- package/dist/chunk-SOXFMMXC.js +151 -0
- package/dist/chunk-TDTYV6QI.js +119 -0
- package/dist/chunk-TNTXWSYA.js +19 -0
- package/dist/chunk-TUXQ32WE.js +2251 -0
- package/dist/chunk-VGCDRK3S.js +37 -0
- package/dist/chunk-VLRHFMGJ.js +58 -0
- package/dist/chunk-WHX2ZFCG.js +4048 -0
- package/dist/chunk-X4W64MHU.js +2005 -0
- package/dist/chunk-XBQA4I36.js +92 -0
- package/dist/chunk-XGOV6KV4.js +413 -0
- package/dist/chunk-XIFQIFSZ.js +940 -0
- package/dist/chunk-XLXPVN3Y.js +15393 -0
- package/dist/chunk-ZJMLQ37G.js +90 -0
- package/dist/client-MU4EUDZV.js +15 -0
- package/dist/commands-UOOTMBKA.js +1023 -0
- package/dist/compat-Q5DVPITN.js +201 -0
- package/dist/constants-DJFOFZ44.js +24 -0
- package/dist/dashboardIssue-KBKLQMGC.js +274 -0
- package/dist/diff-I4SNUHU3.js +13 -0
- package/dist/dist-4XXIXHHZ.js +12945 -0
- package/dist/domains-VRT4BRVZ.js +14 -0
- package/dist/e2b-FVPHDULZ.js +172 -0
- package/dist/env-UN6KGZ7S.js +15 -0
- package/dist/envCheck-KUPTORFQ.js +71 -0
- package/dist/extract-6WG265BL.js +455 -0
- package/dist/fetch-PJ3SC32M.js +22 -0
- package/dist/firstTouch-COJCMOB3.js +55 -0
- package/dist/fix-3EDWNKW3.js +220 -0
- package/dist/handlers-4Q37WIFT.js +55 -0
- package/dist/hook-NA66XJLC.js +412 -0
- package/dist/http-25GJ6SKK.js +6928 -0
- package/dist/ingestQueue-FSVJC3AA.js +37 -0
- package/dist/install-G2HHXYJ2.js +20 -0
- package/dist/installSkill-5TIMYIJZ.js +70 -0
- package/dist/inventory-5AWSLJYU.js +31 -0
- package/dist/local-XPZMRH5R.js +13 -0
- package/dist/manifest-ENMIC54B.js +13 -0
- package/dist/mcp-PENLL2PK.js +500 -0
- package/dist/mcpConfig-3LYPRY5Q.js +80 -0
- package/dist/mcpHandlers-PO7GENA7.js +22 -0
- package/dist/mcpScan-ULP626TQ.js +1735 -0
- package/dist/mcpScanWorkflow-27O44FOE.js +98 -0
- package/dist/mcpStack-ZNYIFXZ5.js +20 -0
- package/dist/model-ASMZWLM7.js +214 -0
- package/dist/packages-RWF2LXST.js +40 -0
- package/dist/plan-SDILIDZT.js +465 -0
- package/dist/planView-ZAKRTGVS.js +82 -0
- package/dist/policy-JAGNMQJI.js +115 -0
- package/dist/probe-3IK646WN.js +610 -0
- package/dist/publicUpgrades-WTBGLDIK.js +42 -0
- package/dist/references-I6Y4BSRR.js +16 -0
- package/dist/release-7IU2R4YG.js +128 -0
- package/dist/remote-FN6225AH.js +42 -0
- package/dist/rename-OS6JYBZQ.js +204 -0
- package/dist/reportRuns-O4X7ZFTX.js +77 -0
- package/dist/safeFetch-COERXGFN.js +19 -0
- package/dist/sandbox-SAPSRKEI.js +39 -0
- package/dist/sarif-WLVJFJ7U.js +125 -0
- package/dist/server-OLTY3NYT.js +59 -0
- package/dist/surface-7MHE3RL7.js +143 -0
- package/dist/surface-JS2XU3U3.js +38 -0
- package/dist/surfaceHandlers-4B6TMZ34.js +20 -0
- package/dist/typecheck-NGOKNAJY.js +282 -0
- package/dist/types-M5JP2W3D.js +10 -0
- package/dist/uninstall-I2IJP5JZ.js +200 -0
- package/dist/upgrade-FS26DJGG.js +650 -0
- package/dist/upgradePlan-ZS5IOVMZ.js +181 -0
- package/dist/upkeepHandler-VFGYXJKB.js +13 -0
- package/dist/userConfig-ICASHI47.js +20 -0
- package/dist/watch-OCNEUXG6.js +204 -0
- package/package.json +26 -20
- package/templates/agent-rules.md +4 -4
- package/templates/skill-instructions.md +35 -17
- package/dist/bin/lurq.js.map +0 -1
- package/dist/index.d.ts +0 -805
- package/dist/index.js +0 -23570
- package/dist/index.js.map +0 -1
- package/drizzle/0000_confused_fabian_cortez.sql +0 -54
- package/drizzle/0001_aspiring_timeslip.sql +0 -15
- package/drizzle/0002_lyrical_lila_cheney.sql +0 -14
- package/drizzle/0003_violet_giant_girl.sql +0 -14
- package/drizzle/0004_slim_valeria_richards.sql +0 -15
- package/drizzle/0005_petite_luke_cage.sql +0 -12
- package/drizzle/0006_calm_nighthawk.sql +0 -3
- package/drizzle/0007_slimy_naoko.sql +0 -1
- package/drizzle/0008_peaceful_tigra.sql +0 -1
- package/drizzle/0009_smooth_harrier.sql +0 -10
- package/drizzle/0010_curved_amphibian.sql +0 -2
- package/drizzle/0011_compat_provenance_closures.sql +0 -11
- package/drizzle/0012_api_surfaces.sql +0 -9
- package/drizzle/0013_nice_thanos.sql +0 -1
- package/drizzle/0014_luxuriant_malcolm_colcord.sql +0 -10
- package/drizzle/0015_past_fat_cobra.sql +0 -11
- package/drizzle/0016_futuristic_junta.sql +0 -50
- package/drizzle/0017_absent_grandmaster.sql +0 -20
- package/drizzle/0018_rainy_proemial_gods.sql +0 -1
- package/drizzle/0019_dashing_korvac.sql +0 -11
- package/drizzle/0020_normal_vulture.sql +0 -3
- package/drizzle/0021_dazzling_blue_shield.sql +0 -17
- package/drizzle/0022_massive_ghost_rider.sql +0 -24
- package/drizzle/0023_next_shatterstar.sql +0 -1
- package/drizzle/0024_dusty_maelstrom.sql +0 -15
- package/drizzle/0025_gifted_harpoon.sql +0 -5
- package/drizzle/0026_awesome_mordo.sql +0 -1
- package/drizzle/0027_charming_ulik.sql +0 -2
- package/drizzle/0028_romantic_loners.sql +0 -2
- package/drizzle/0029_busy_korvac.sql +0 -16
- package/drizzle/0030_steady_mathemanic.sql +0 -6
- package/drizzle/0031_redundant_maginty.sql +0 -2
- package/drizzle/0032_stack_resolutions.sql +0 -14
- package/drizzle/0033_graceful_tyger_tiger.sql +0 -3
- package/drizzle/0034_uneven_thunderbird.sql +0 -1
- package/drizzle/0035_api_key_scopes.sql +0 -1
- package/drizzle/0036_policy_audit.sql +0 -21
- package/drizzle/0037_subscription_seats.sql +0 -1
- package/drizzle/0038_symbol_offsets.sql +0 -2
- package/drizzle/0039_mcp_runtime_scans.sql +0 -80
- package/drizzle/0040_subscription_overage_and_interval.sql +0 -4
- package/drizzle/0041_account_email.sql +0 -38
- package/drizzle/0042_alert_channels.sql +0 -21
- package/drizzle/meta/0000_snapshot.json +0 -370
- package/drizzle/meta/0001_snapshot.json +0 -482
- package/drizzle/meta/0002_snapshot.json +0 -575
- package/drizzle/meta/0003_snapshot.json +0 -667
- package/drizzle/meta/0004_snapshot.json +0 -769
- package/drizzle/meta/0005_snapshot.json +0 -864
- package/drizzle/meta/0006_snapshot.json +0 -882
- package/drizzle/meta/0007_snapshot.json +0 -876
- package/drizzle/meta/0008_snapshot.json +0 -882
- package/drizzle/meta/0009_snapshot.json +0 -948
- package/drizzle/meta/0010_snapshot.json +0 -969
- package/drizzle/meta/0011_snapshot.json +0 -1049
- package/drizzle/meta/0012_snapshot.json +0 -1115
- package/drizzle/meta/0013_snapshot.json +0 -1121
- package/drizzle/meta/0014_snapshot.json +0 -1190
- package/drizzle/meta/0015_snapshot.json +0 -1280
- package/drizzle/meta/0016_snapshot.json +0 -1683
- package/drizzle/meta/0017_snapshot.json +0 -1834
- package/drizzle/meta/0018_snapshot.json +0 -1834
- package/drizzle/meta/0019_snapshot.json +0 -1909
- package/drizzle/meta/0020_snapshot.json +0 -1921
- package/drizzle/meta/0021_snapshot.json +0 -2045
- package/drizzle/meta/0022_snapshot.json +0 -2246
- package/drizzle/meta/0023_snapshot.json +0 -2252
- package/drizzle/meta/0024_snapshot.json +0 -2375
- package/drizzle/meta/0025_snapshot.json +0 -2407
- package/drizzle/meta/0026_snapshot.json +0 -2413
- package/drizzle/meta/0027_snapshot.json +0 -2425
- package/drizzle/meta/0028_snapshot.json +0 -2438
- package/drizzle/meta/0029_snapshot.json +0 -2546
- package/drizzle/meta/0030_snapshot.json +0 -2586
- package/drizzle/meta/0031_snapshot.json +0 -2598
- package/drizzle/meta/0032_snapshot.json +0 -2699
- package/drizzle/meta/0033_snapshot.json +0 -2712
- package/drizzle/meta/0034_snapshot.json +0 -2719
- package/drizzle/meta/0035_snapshot.json +0 -2726
- package/drizzle/meta/0036_snapshot.json +0 -2876
- package/drizzle/meta/0037_snapshot.json +0 -2883
- package/drizzle/meta/0038_snapshot.json +0 -2895
- package/drizzle/meta/0039_snapshot.json +0 -3501
- package/drizzle/meta/0040_snapshot.json +0 -3527
- package/drizzle/meta/0041_snapshot.json +0 -3824
- package/drizzle/meta/0042_snapshot.json +0 -3960
- package/drizzle/meta/_journal.json +0 -307
- package/src/data/seed.json +0 -253
|
@@ -0,0 +1,2005 @@
|
|
|
1
|
+
import { createRequire as __lurqCreateRequire } from 'node:module'; const require = __lurqCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
JSONRPCMessageSchema,
|
|
4
|
+
LATEST_PROTOCOL_VERSION,
|
|
5
|
+
NEVER,
|
|
6
|
+
ZodIssueCode,
|
|
7
|
+
any,
|
|
8
|
+
array,
|
|
9
|
+
boolean,
|
|
10
|
+
coerce_exports,
|
|
11
|
+
isInitializedNotification,
|
|
12
|
+
isJSONRPCRequest,
|
|
13
|
+
isJSONRPCResultResponse,
|
|
14
|
+
literal,
|
|
15
|
+
looseObject,
|
|
16
|
+
number,
|
|
17
|
+
object,
|
|
18
|
+
string,
|
|
19
|
+
url
|
|
20
|
+
} from "./chunk-D3K6IZVR.js";
|
|
21
|
+
import {
|
|
22
|
+
init_esm_shims
|
|
23
|
+
} from "./chunk-I3M2KJXB.js";
|
|
24
|
+
|
|
25
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
|
|
26
|
+
init_esm_shims();
|
|
27
|
+
|
|
28
|
+
// node_modules/eventsource/dist/index.js
|
|
29
|
+
init_esm_shims();
|
|
30
|
+
|
|
31
|
+
// node_modules/eventsource-parser/dist/index.js
|
|
32
|
+
init_esm_shims();
|
|
33
|
+
var ParseError = class extends Error {
|
|
34
|
+
constructor(message, options) {
|
|
35
|
+
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var LF = 10;
|
|
39
|
+
var CR = 13;
|
|
40
|
+
var SPACE = 32;
|
|
41
|
+
function noop(_arg) {
|
|
42
|
+
}
|
|
43
|
+
function createParser(config) {
|
|
44
|
+
if (typeof config == "function")
|
|
45
|
+
throw new TypeError(
|
|
46
|
+
"`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
|
|
47
|
+
);
|
|
48
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
|
|
49
|
+
let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
|
|
50
|
+
function feed(chunk) {
|
|
51
|
+
if (terminated)
|
|
52
|
+
throw new Error(
|
|
53
|
+
"Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
|
|
54
|
+
);
|
|
55
|
+
if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
|
|
56
|
+
const trailing2 = processLines(chunk);
|
|
57
|
+
trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (chunk.indexOf(`
|
|
61
|
+
`) === -1 && chunk.indexOf("\r") === -1) {
|
|
62
|
+
pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
pendingFragments.push(chunk);
|
|
66
|
+
const input = pendingFragments.join("");
|
|
67
|
+
pendingFragments.length = 0, pendingFragmentsLength = 0;
|
|
68
|
+
const trailing = processLines(input);
|
|
69
|
+
trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
|
|
70
|
+
}
|
|
71
|
+
function checkBufferSize() {
|
|
72
|
+
maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
|
|
73
|
+
new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
|
|
74
|
+
type: "max-buffer-size-exceeded"
|
|
75
|
+
})
|
|
76
|
+
)));
|
|
77
|
+
}
|
|
78
|
+
function processLines(chunk) {
|
|
79
|
+
let searchIndex = 0;
|
|
80
|
+
if (chunk.indexOf("\r") === -1) {
|
|
81
|
+
let lfIndex = chunk.indexOf(`
|
|
82
|
+
`, searchIndex);
|
|
83
|
+
for (; lfIndex !== -1; ) {
|
|
84
|
+
if (searchIndex === lfIndex) {
|
|
85
|
+
dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
|
|
86
|
+
`, searchIndex);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const firstCharCode = chunk.charCodeAt(searchIndex);
|
|
90
|
+
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
|
|
91
|
+
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
|
|
92
|
+
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
|
|
93
|
+
onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
|
|
94
|
+
`, searchIndex);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
data = dataLines === 0 ? value : `${data}
|
|
98
|
+
${value}`, dataLines++;
|
|
99
|
+
} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
|
|
100
|
+
chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
|
|
101
|
+
lfIndex
|
|
102
|
+
) || void 0 : parseLine(chunk, searchIndex, lfIndex);
|
|
103
|
+
searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
|
|
104
|
+
`, searchIndex);
|
|
105
|
+
}
|
|
106
|
+
return chunk.slice(searchIndex);
|
|
107
|
+
}
|
|
108
|
+
for (; searchIndex < chunk.length; ) {
|
|
109
|
+
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
|
|
110
|
+
`, searchIndex);
|
|
111
|
+
let lineEnd = -1;
|
|
112
|
+
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
|
|
113
|
+
break;
|
|
114
|
+
parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
|
|
115
|
+
}
|
|
116
|
+
return chunk.slice(searchIndex);
|
|
117
|
+
}
|
|
118
|
+
function parseLine(chunk, start, end) {
|
|
119
|
+
if (start === end) {
|
|
120
|
+
dispatchEvent();
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const firstCharCode = chunk.charCodeAt(start);
|
|
124
|
+
if (isDataPrefix(chunk, start, firstCharCode)) {
|
|
125
|
+
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
|
|
126
|
+
data = dataLines === 0 ? value2 : `${data}
|
|
127
|
+
${value2}`, dataLines++;
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (isEventPrefix(chunk, start, firstCharCode)) {
|
|
131
|
+
eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
|
|
135
|
+
const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
|
|
136
|
+
id = value2.includes("\0") ? void 0 : value2;
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (firstCharCode === 58) {
|
|
140
|
+
if (onComment) {
|
|
141
|
+
const line2 = chunk.slice(start, end);
|
|
142
|
+
onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
|
|
147
|
+
if (fieldSeparatorIndex === -1) {
|
|
148
|
+
processField(line, "", line);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
|
|
152
|
+
processField(field, value, line);
|
|
153
|
+
}
|
|
154
|
+
function processField(field, value, line) {
|
|
155
|
+
switch (field) {
|
|
156
|
+
case "event":
|
|
157
|
+
eventType = value || void 0;
|
|
158
|
+
break;
|
|
159
|
+
case "data":
|
|
160
|
+
data = dataLines === 0 ? value : `${data}
|
|
161
|
+
${value}`, dataLines++;
|
|
162
|
+
break;
|
|
163
|
+
case "id":
|
|
164
|
+
id = value.includes("\0") ? void 0 : value;
|
|
165
|
+
break;
|
|
166
|
+
case "retry":
|
|
167
|
+
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
|
|
168
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
169
|
+
type: "invalid-retry",
|
|
170
|
+
value,
|
|
171
|
+
line
|
|
172
|
+
})
|
|
173
|
+
);
|
|
174
|
+
break;
|
|
175
|
+
default:
|
|
176
|
+
onError(
|
|
177
|
+
new ParseError(
|
|
178
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
179
|
+
{ type: "unknown-field", field, value, line }
|
|
180
|
+
)
|
|
181
|
+
);
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function dispatchEvent() {
|
|
186
|
+
dataLines > 0 && onEvent({
|
|
187
|
+
id,
|
|
188
|
+
event: eventType,
|
|
189
|
+
data
|
|
190
|
+
}), id = void 0, data = "", dataLines = 0, eventType = void 0;
|
|
191
|
+
}
|
|
192
|
+
function reset(options = {}) {
|
|
193
|
+
if (options.consume && pendingFragments.length > 0) {
|
|
194
|
+
const incompleteLine = pendingFragments.join("");
|
|
195
|
+
parseLine(incompleteLine, 0, incompleteLine.length);
|
|
196
|
+
}
|
|
197
|
+
isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
|
|
198
|
+
}
|
|
199
|
+
return { feed, reset };
|
|
200
|
+
}
|
|
201
|
+
function isDataPrefix(chunk, i, firstCharCode) {
|
|
202
|
+
return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
|
|
203
|
+
}
|
|
204
|
+
function isEventPrefix(chunk, i, firstCharCode) {
|
|
205
|
+
return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// node_modules/eventsource/dist/index.js
|
|
209
|
+
var ErrorEvent = class extends Event {
|
|
210
|
+
/**
|
|
211
|
+
* Constructs a new `ErrorEvent` instance. This is typically not called directly,
|
|
212
|
+
* but rather emitted by the `EventSource` object when an error occurs.
|
|
213
|
+
*
|
|
214
|
+
* @param type - The type of the event (should be "error")
|
|
215
|
+
* @param errorEventInitDict - Optional properties to include in the error event
|
|
216
|
+
*/
|
|
217
|
+
constructor(type, errorEventInitDict) {
|
|
218
|
+
var _a, _b;
|
|
219
|
+
super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
|
|
223
|
+
* when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
|
|
224
|
+
* we explicitly include the properties in the `inspect` method.
|
|
225
|
+
*
|
|
226
|
+
* This is automatically called by Node.js when you `console.log` an instance of this class.
|
|
227
|
+
*
|
|
228
|
+
* @param _depth - The current depth
|
|
229
|
+
* @param options - The options passed to `util.inspect`
|
|
230
|
+
* @param inspect - The inspect function to use (prevents having to import it from `util`)
|
|
231
|
+
* @returns A string representation of the error
|
|
232
|
+
*/
|
|
233
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
|
|
234
|
+
return inspect(inspectableError(this), options);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
|
|
238
|
+
* when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
|
|
239
|
+
* we explicitly include the properties in the `inspect` method.
|
|
240
|
+
*
|
|
241
|
+
* This is automatically called by Deno when you `console.log` an instance of this class.
|
|
242
|
+
*
|
|
243
|
+
* @param inspect - The inspect function to use (prevents having to import it from `util`)
|
|
244
|
+
* @param options - The options passed to `Deno.inspect`
|
|
245
|
+
* @returns A string representation of the error
|
|
246
|
+
*/
|
|
247
|
+
[/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) {
|
|
248
|
+
return inspect(inspectableError(this), options);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
function syntaxError(message) {
|
|
252
|
+
const DomException = globalThis.DOMException;
|
|
253
|
+
return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
|
|
254
|
+
}
|
|
255
|
+
function flattenError(err) {
|
|
256
|
+
return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
|
|
257
|
+
}
|
|
258
|
+
function inspectableError(err) {
|
|
259
|
+
return {
|
|
260
|
+
type: err.type,
|
|
261
|
+
message: err.message,
|
|
262
|
+
code: err.code,
|
|
263
|
+
defaultPrevented: err.defaultPrevented,
|
|
264
|
+
cancelable: err.cancelable,
|
|
265
|
+
timeStamp: err.timeStamp
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
var __typeError = (msg) => {
|
|
269
|
+
throw TypeError(msg);
|
|
270
|
+
};
|
|
271
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
272
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
273
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
274
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
275
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
276
|
+
var _readyState;
|
|
277
|
+
var _url;
|
|
278
|
+
var _redirectUrl;
|
|
279
|
+
var _withCredentials;
|
|
280
|
+
var _fetch;
|
|
281
|
+
var _reconnectInterval;
|
|
282
|
+
var _reconnectTimer;
|
|
283
|
+
var _lastEventId;
|
|
284
|
+
var _controller;
|
|
285
|
+
var _parser;
|
|
286
|
+
var _onError;
|
|
287
|
+
var _onMessage;
|
|
288
|
+
var _onOpen;
|
|
289
|
+
var _EventSource_instances;
|
|
290
|
+
var connect_fn;
|
|
291
|
+
var _onFetchResponse;
|
|
292
|
+
var _onFetchError;
|
|
293
|
+
var getRequestOptions_fn;
|
|
294
|
+
var _onEvent;
|
|
295
|
+
var _onRetryChange;
|
|
296
|
+
var failConnection_fn;
|
|
297
|
+
var scheduleReconnect_fn;
|
|
298
|
+
var _reconnect;
|
|
299
|
+
var EventSource = class extends EventTarget {
|
|
300
|
+
constructor(url2, eventSourceInitDict) {
|
|
301
|
+
var _a, _b;
|
|
302
|
+
super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
|
|
303
|
+
var _a2;
|
|
304
|
+
__privateGet(this, _parser).reset();
|
|
305
|
+
const { body, redirected, status, headers } = response;
|
|
306
|
+
if (status === 204) {
|
|
307
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
|
|
311
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
|
|
315
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (__privateGet(this, _readyState) === this.CLOSED)
|
|
319
|
+
return;
|
|
320
|
+
__privateSet(this, _readyState, this.OPEN);
|
|
321
|
+
const openEvent = new Event("open");
|
|
322
|
+
if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
|
|
323
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const decoder = new TextDecoder(), reader = body.getReader();
|
|
327
|
+
let open = true;
|
|
328
|
+
do {
|
|
329
|
+
const { done, value } = await reader.read();
|
|
330
|
+
value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
|
|
331
|
+
} while (open);
|
|
332
|
+
}), __privateAdd(this, _onFetchError, (err) => {
|
|
333
|
+
__privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
|
|
334
|
+
}), __privateAdd(this, _onEvent, (event) => {
|
|
335
|
+
typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
|
|
336
|
+
const messageEvent = new MessageEvent(event.event || "message", {
|
|
337
|
+
data: event.data,
|
|
338
|
+
origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
|
|
339
|
+
lastEventId: event.id || ""
|
|
340
|
+
});
|
|
341
|
+
__privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
|
|
342
|
+
}), __privateAdd(this, _onRetryChange, (value) => {
|
|
343
|
+
__privateSet(this, _reconnectInterval, value);
|
|
344
|
+
}), __privateAdd(this, _reconnect, () => {
|
|
345
|
+
__privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
|
|
346
|
+
});
|
|
347
|
+
try {
|
|
348
|
+
if (url2 instanceof URL)
|
|
349
|
+
__privateSet(this, _url, url2);
|
|
350
|
+
else if (typeof url2 == "string")
|
|
351
|
+
__privateSet(this, _url, new URL(url2, getBaseURL()));
|
|
352
|
+
else
|
|
353
|
+
throw new Error("Invalid URL");
|
|
354
|
+
} catch {
|
|
355
|
+
throw syntaxError("An invalid or illegal string was specified");
|
|
356
|
+
}
|
|
357
|
+
__privateSet(this, _parser, createParser({
|
|
358
|
+
onEvent: __privateGet(this, _onEvent),
|
|
359
|
+
onRetry: __privateGet(this, _onRetryChange)
|
|
360
|
+
})), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Returns the state of this EventSource object's connection. It can have the values described below.
|
|
364
|
+
*
|
|
365
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
|
|
366
|
+
*
|
|
367
|
+
* Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
|
|
368
|
+
* defined in the TypeScript `dom` library.
|
|
369
|
+
*
|
|
370
|
+
* @public
|
|
371
|
+
*/
|
|
372
|
+
get readyState() {
|
|
373
|
+
return __privateGet(this, _readyState);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Returns the URL providing the event stream.
|
|
377
|
+
*
|
|
378
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
|
|
379
|
+
*
|
|
380
|
+
* @public
|
|
381
|
+
*/
|
|
382
|
+
get url() {
|
|
383
|
+
return __privateGet(this, _url).href;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
|
|
387
|
+
*
|
|
388
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
|
|
389
|
+
*/
|
|
390
|
+
get withCredentials() {
|
|
391
|
+
return __privateGet(this, _withCredentials);
|
|
392
|
+
}
|
|
393
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
|
|
394
|
+
get onerror() {
|
|
395
|
+
return __privateGet(this, _onError);
|
|
396
|
+
}
|
|
397
|
+
set onerror(value) {
|
|
398
|
+
__privateSet(this, _onError, value);
|
|
399
|
+
}
|
|
400
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
|
|
401
|
+
get onmessage() {
|
|
402
|
+
return __privateGet(this, _onMessage);
|
|
403
|
+
}
|
|
404
|
+
set onmessage(value) {
|
|
405
|
+
__privateSet(this, _onMessage, value);
|
|
406
|
+
}
|
|
407
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
|
|
408
|
+
get onopen() {
|
|
409
|
+
return __privateGet(this, _onOpen);
|
|
410
|
+
}
|
|
411
|
+
set onopen(value) {
|
|
412
|
+
__privateSet(this, _onOpen, value);
|
|
413
|
+
}
|
|
414
|
+
addEventListener(type, listener, options) {
|
|
415
|
+
const listen = listener;
|
|
416
|
+
super.addEventListener(type, listen, options);
|
|
417
|
+
}
|
|
418
|
+
removeEventListener(type, listener, options) {
|
|
419
|
+
const listen = listener;
|
|
420
|
+
super.removeEventListener(type, listen, options);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
|
|
424
|
+
*
|
|
425
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
|
|
426
|
+
*
|
|
427
|
+
* @public
|
|
428
|
+
*/
|
|
429
|
+
close() {
|
|
430
|
+
__privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
|
|
434
|
+
* Connect to the given URL and start receiving events
|
|
435
|
+
*
|
|
436
|
+
* @internal
|
|
437
|
+
*/
|
|
438
|
+
connect_fn = function() {
|
|
439
|
+
__privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
|
|
440
|
+
}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
|
|
441
|
+
* Get request options for the `fetch()` request
|
|
442
|
+
*
|
|
443
|
+
* @returns The request options
|
|
444
|
+
* @internal
|
|
445
|
+
*/
|
|
446
|
+
getRequestOptions_fn = function() {
|
|
447
|
+
var _a;
|
|
448
|
+
const init = {
|
|
449
|
+
// [spec] Let `corsAttributeState` be `Anonymous`…
|
|
450
|
+
// [spec] …will have their mode set to "cors"…
|
|
451
|
+
mode: "cors",
|
|
452
|
+
redirect: "follow",
|
|
453
|
+
headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
|
|
454
|
+
cache: "no-store",
|
|
455
|
+
signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
|
|
456
|
+
};
|
|
457
|
+
return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
|
|
458
|
+
}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
|
|
459
|
+
* Handles the process referred to in the EventSource specification as "failing a connection".
|
|
460
|
+
*
|
|
461
|
+
* @param error - The error causing the connection to fail
|
|
462
|
+
* @param code - The HTTP status code, if available
|
|
463
|
+
* @internal
|
|
464
|
+
*/
|
|
465
|
+
failConnection_fn = function(message, code) {
|
|
466
|
+
var _a;
|
|
467
|
+
__privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
|
|
468
|
+
const errorEvent = new ErrorEvent("error", { code, message });
|
|
469
|
+
(_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
|
|
470
|
+
}, /**
|
|
471
|
+
* Schedules a reconnection attempt against the EventSource endpoint.
|
|
472
|
+
*
|
|
473
|
+
* @param message - The error causing the connection to fail
|
|
474
|
+
* @param code - The HTTP status code, if available
|
|
475
|
+
* @internal
|
|
476
|
+
*/
|
|
477
|
+
scheduleReconnect_fn = function(message, code) {
|
|
478
|
+
var _a;
|
|
479
|
+
if (__privateGet(this, _readyState) === this.CLOSED)
|
|
480
|
+
return;
|
|
481
|
+
__privateSet(this, _readyState, this.CONNECTING);
|
|
482
|
+
const errorEvent = new ErrorEvent("error", { code, message });
|
|
483
|
+
(_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
|
|
484
|
+
}, _reconnect = /* @__PURE__ */ new WeakMap(), /**
|
|
485
|
+
* ReadyState representing an EventSource currently trying to connect
|
|
486
|
+
*
|
|
487
|
+
* @public
|
|
488
|
+
*/
|
|
489
|
+
EventSource.CONNECTING = 0, /**
|
|
490
|
+
* ReadyState representing an EventSource connection that is open (eg connected)
|
|
491
|
+
*
|
|
492
|
+
* @public
|
|
493
|
+
*/
|
|
494
|
+
EventSource.OPEN = 1, /**
|
|
495
|
+
* ReadyState representing an EventSource connection that is closed (eg disconnected)
|
|
496
|
+
*
|
|
497
|
+
* @public
|
|
498
|
+
*/
|
|
499
|
+
EventSource.CLOSED = 2;
|
|
500
|
+
function getBaseURL() {
|
|
501
|
+
const doc = "document" in globalThis ? globalThis.document : void 0;
|
|
502
|
+
return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
|
|
506
|
+
init_esm_shims();
|
|
507
|
+
function normalizeHeaders(headers) {
|
|
508
|
+
if (!headers)
|
|
509
|
+
return {};
|
|
510
|
+
if (headers instanceof Headers) {
|
|
511
|
+
return Object.fromEntries(headers.entries());
|
|
512
|
+
}
|
|
513
|
+
if (Array.isArray(headers)) {
|
|
514
|
+
return Object.fromEntries(headers);
|
|
515
|
+
}
|
|
516
|
+
return { ...headers };
|
|
517
|
+
}
|
|
518
|
+
function createFetchWithInit(baseFetch = fetch, baseInit) {
|
|
519
|
+
if (!baseInit) {
|
|
520
|
+
return baseFetch;
|
|
521
|
+
}
|
|
522
|
+
return async (url2, init) => {
|
|
523
|
+
const mergedInit = {
|
|
524
|
+
...baseInit,
|
|
525
|
+
...init,
|
|
526
|
+
// Headers need special handling - merge instead of replace
|
|
527
|
+
headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
|
|
528
|
+
};
|
|
529
|
+
return baseFetch(url2, mergedInit);
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
|
|
534
|
+
init_esm_shims();
|
|
535
|
+
|
|
536
|
+
// node_modules/pkce-challenge/dist/index.node.js
|
|
537
|
+
init_esm_shims();
|
|
538
|
+
var crypto;
|
|
539
|
+
crypto = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
|
|
540
|
+
globalThis.crypto ?? // Node.js >18
|
|
541
|
+
import("crypto").then((m) => m.webcrypto);
|
|
542
|
+
async function getRandomValues(size) {
|
|
543
|
+
return (await crypto).getRandomValues(new Uint8Array(size));
|
|
544
|
+
}
|
|
545
|
+
async function random(size) {
|
|
546
|
+
const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
|
547
|
+
const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
|
|
548
|
+
let result = "";
|
|
549
|
+
while (result.length < size) {
|
|
550
|
+
const randomBytes = await getRandomValues(size - result.length);
|
|
551
|
+
for (const randomByte of randomBytes) {
|
|
552
|
+
if (randomByte < evenDistCutoff) {
|
|
553
|
+
result += mask[randomByte % mask.length];
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return result;
|
|
558
|
+
}
|
|
559
|
+
async function generateVerifier(length) {
|
|
560
|
+
return await random(length);
|
|
561
|
+
}
|
|
562
|
+
async function generateChallenge(code_verifier) {
|
|
563
|
+
const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
|
|
564
|
+
return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
|
|
565
|
+
}
|
|
566
|
+
async function pkceChallenge(length) {
|
|
567
|
+
if (!length)
|
|
568
|
+
length = 43;
|
|
569
|
+
if (length < 43 || length > 128) {
|
|
570
|
+
throw `Expected a length between 43 and 128. Received ${length}.`;
|
|
571
|
+
}
|
|
572
|
+
const verifier = await generateVerifier(length);
|
|
573
|
+
const challenge = await generateChallenge(verifier);
|
|
574
|
+
return {
|
|
575
|
+
code_verifier: verifier,
|
|
576
|
+
code_challenge: challenge
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
|
|
581
|
+
init_esm_shims();
|
|
582
|
+
var SafeUrlSchema = url().superRefine((val, ctx) => {
|
|
583
|
+
if (!URL.canParse(val)) {
|
|
584
|
+
ctx.addIssue({
|
|
585
|
+
code: ZodIssueCode.custom,
|
|
586
|
+
message: "URL must be parseable",
|
|
587
|
+
fatal: true
|
|
588
|
+
});
|
|
589
|
+
return NEVER;
|
|
590
|
+
}
|
|
591
|
+
}).refine((url2) => {
|
|
592
|
+
const u = new URL(url2);
|
|
593
|
+
return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
|
|
594
|
+
}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
|
|
595
|
+
var OAuthProtectedResourceMetadataSchema = looseObject({
|
|
596
|
+
resource: string().url(),
|
|
597
|
+
authorization_servers: array(SafeUrlSchema).optional(),
|
|
598
|
+
jwks_uri: string().url().optional(),
|
|
599
|
+
scopes_supported: array(string()).optional(),
|
|
600
|
+
bearer_methods_supported: array(string()).optional(),
|
|
601
|
+
resource_signing_alg_values_supported: array(string()).optional(),
|
|
602
|
+
resource_name: string().optional(),
|
|
603
|
+
resource_documentation: string().optional(),
|
|
604
|
+
resource_policy_uri: string().url().optional(),
|
|
605
|
+
resource_tos_uri: string().url().optional(),
|
|
606
|
+
tls_client_certificate_bound_access_tokens: boolean().optional(),
|
|
607
|
+
authorization_details_types_supported: array(string()).optional(),
|
|
608
|
+
dpop_signing_alg_values_supported: array(string()).optional(),
|
|
609
|
+
dpop_bound_access_tokens_required: boolean().optional()
|
|
610
|
+
});
|
|
611
|
+
var OAuthMetadataSchema = looseObject({
|
|
612
|
+
issuer: string(),
|
|
613
|
+
authorization_endpoint: SafeUrlSchema,
|
|
614
|
+
token_endpoint: SafeUrlSchema,
|
|
615
|
+
registration_endpoint: SafeUrlSchema.optional(),
|
|
616
|
+
scopes_supported: array(string()).optional(),
|
|
617
|
+
response_types_supported: array(string()),
|
|
618
|
+
response_modes_supported: array(string()).optional(),
|
|
619
|
+
grant_types_supported: array(string()).optional(),
|
|
620
|
+
token_endpoint_auth_methods_supported: array(string()).optional(),
|
|
621
|
+
token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
622
|
+
service_documentation: SafeUrlSchema.optional(),
|
|
623
|
+
revocation_endpoint: SafeUrlSchema.optional(),
|
|
624
|
+
revocation_endpoint_auth_methods_supported: array(string()).optional(),
|
|
625
|
+
revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
626
|
+
introspection_endpoint: string().optional(),
|
|
627
|
+
introspection_endpoint_auth_methods_supported: array(string()).optional(),
|
|
628
|
+
introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
629
|
+
code_challenge_methods_supported: array(string()).optional(),
|
|
630
|
+
client_id_metadata_document_supported: boolean().optional()
|
|
631
|
+
});
|
|
632
|
+
var OpenIdProviderMetadataSchema = looseObject({
|
|
633
|
+
issuer: string(),
|
|
634
|
+
authorization_endpoint: SafeUrlSchema,
|
|
635
|
+
token_endpoint: SafeUrlSchema,
|
|
636
|
+
userinfo_endpoint: SafeUrlSchema.optional(),
|
|
637
|
+
jwks_uri: SafeUrlSchema,
|
|
638
|
+
registration_endpoint: SafeUrlSchema.optional(),
|
|
639
|
+
scopes_supported: array(string()).optional(),
|
|
640
|
+
response_types_supported: array(string()),
|
|
641
|
+
response_modes_supported: array(string()).optional(),
|
|
642
|
+
grant_types_supported: array(string()).optional(),
|
|
643
|
+
acr_values_supported: array(string()).optional(),
|
|
644
|
+
subject_types_supported: array(string()),
|
|
645
|
+
id_token_signing_alg_values_supported: array(string()),
|
|
646
|
+
id_token_encryption_alg_values_supported: array(string()).optional(),
|
|
647
|
+
id_token_encryption_enc_values_supported: array(string()).optional(),
|
|
648
|
+
userinfo_signing_alg_values_supported: array(string()).optional(),
|
|
649
|
+
userinfo_encryption_alg_values_supported: array(string()).optional(),
|
|
650
|
+
userinfo_encryption_enc_values_supported: array(string()).optional(),
|
|
651
|
+
request_object_signing_alg_values_supported: array(string()).optional(),
|
|
652
|
+
request_object_encryption_alg_values_supported: array(string()).optional(),
|
|
653
|
+
request_object_encryption_enc_values_supported: array(string()).optional(),
|
|
654
|
+
token_endpoint_auth_methods_supported: array(string()).optional(),
|
|
655
|
+
token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
656
|
+
display_values_supported: array(string()).optional(),
|
|
657
|
+
claim_types_supported: array(string()).optional(),
|
|
658
|
+
claims_supported: array(string()).optional(),
|
|
659
|
+
service_documentation: string().optional(),
|
|
660
|
+
claims_locales_supported: array(string()).optional(),
|
|
661
|
+
ui_locales_supported: array(string()).optional(),
|
|
662
|
+
claims_parameter_supported: boolean().optional(),
|
|
663
|
+
request_parameter_supported: boolean().optional(),
|
|
664
|
+
request_uri_parameter_supported: boolean().optional(),
|
|
665
|
+
require_request_uri_registration: boolean().optional(),
|
|
666
|
+
op_policy_uri: SafeUrlSchema.optional(),
|
|
667
|
+
op_tos_uri: SafeUrlSchema.optional(),
|
|
668
|
+
client_id_metadata_document_supported: boolean().optional()
|
|
669
|
+
});
|
|
670
|
+
var OpenIdProviderDiscoveryMetadataSchema = object({
|
|
671
|
+
...OpenIdProviderMetadataSchema.shape,
|
|
672
|
+
...OAuthMetadataSchema.pick({
|
|
673
|
+
code_challenge_methods_supported: true
|
|
674
|
+
}).shape
|
|
675
|
+
});
|
|
676
|
+
var OAuthTokensSchema = object({
|
|
677
|
+
access_token: string(),
|
|
678
|
+
id_token: string().optional(),
|
|
679
|
+
// Optional for OAuth 2.1, but necessary in OpenID Connect
|
|
680
|
+
token_type: string(),
|
|
681
|
+
expires_in: coerce_exports.number().optional(),
|
|
682
|
+
scope: string().optional(),
|
|
683
|
+
refresh_token: string().optional()
|
|
684
|
+
}).strip();
|
|
685
|
+
var OAuthErrorResponseSchema = object({
|
|
686
|
+
error: string(),
|
|
687
|
+
error_description: string().optional(),
|
|
688
|
+
error_uri: string().optional()
|
|
689
|
+
});
|
|
690
|
+
var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
|
|
691
|
+
var OAuthClientMetadataSchema = object({
|
|
692
|
+
redirect_uris: array(SafeUrlSchema),
|
|
693
|
+
token_endpoint_auth_method: string().optional(),
|
|
694
|
+
grant_types: array(string()).optional(),
|
|
695
|
+
response_types: array(string()).optional(),
|
|
696
|
+
client_name: string().optional(),
|
|
697
|
+
client_uri: SafeUrlSchema.optional(),
|
|
698
|
+
logo_uri: OptionalSafeUrlSchema,
|
|
699
|
+
scope: string().optional(),
|
|
700
|
+
contacts: array(string()).optional(),
|
|
701
|
+
tos_uri: OptionalSafeUrlSchema,
|
|
702
|
+
policy_uri: string().optional(),
|
|
703
|
+
jwks_uri: SafeUrlSchema.optional(),
|
|
704
|
+
jwks: any().optional(),
|
|
705
|
+
software_id: string().optional(),
|
|
706
|
+
software_version: string().optional(),
|
|
707
|
+
software_statement: string().optional()
|
|
708
|
+
}).strip();
|
|
709
|
+
var OAuthClientInformationSchema = object({
|
|
710
|
+
client_id: string(),
|
|
711
|
+
client_secret: string().optional(),
|
|
712
|
+
client_id_issued_at: number().optional(),
|
|
713
|
+
client_secret_expires_at: number().optional()
|
|
714
|
+
}).strip();
|
|
715
|
+
var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
|
|
716
|
+
var OAuthClientRegistrationErrorSchema = object({
|
|
717
|
+
error: string(),
|
|
718
|
+
error_description: string().optional()
|
|
719
|
+
}).strip();
|
|
720
|
+
var OAuthTokenRevocationRequestSchema = object({
|
|
721
|
+
token: string(),
|
|
722
|
+
token_type_hint: string().optional()
|
|
723
|
+
}).strip();
|
|
724
|
+
|
|
725
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
|
|
726
|
+
init_esm_shims();
|
|
727
|
+
function resourceUrlFromServerUrl(url2) {
|
|
728
|
+
const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
|
|
729
|
+
resourceURL.hash = "";
|
|
730
|
+
return resourceURL;
|
|
731
|
+
}
|
|
732
|
+
function checkResourceAllowed({ requestedResource, configuredResource }) {
|
|
733
|
+
const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
|
|
734
|
+
const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
|
|
735
|
+
if (requested.origin !== configured.origin) {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
if (requested.pathname.length < configured.pathname.length) {
|
|
739
|
+
return false;
|
|
740
|
+
}
|
|
741
|
+
const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
|
|
742
|
+
const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
|
|
743
|
+
return requestedPath.startsWith(configuredPath);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
|
|
747
|
+
init_esm_shims();
|
|
748
|
+
var OAuthError = class extends Error {
|
|
749
|
+
constructor(message, errorUri) {
|
|
750
|
+
super(message);
|
|
751
|
+
this.errorUri = errorUri;
|
|
752
|
+
this.name = this.constructor.name;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Converts the error to a standard OAuth error response object
|
|
756
|
+
*/
|
|
757
|
+
toResponseObject() {
|
|
758
|
+
const response = {
|
|
759
|
+
error: this.errorCode,
|
|
760
|
+
error_description: this.message
|
|
761
|
+
};
|
|
762
|
+
if (this.errorUri) {
|
|
763
|
+
response.error_uri = this.errorUri;
|
|
764
|
+
}
|
|
765
|
+
return response;
|
|
766
|
+
}
|
|
767
|
+
get errorCode() {
|
|
768
|
+
return this.constructor.errorCode;
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
var InvalidRequestError = class extends OAuthError {
|
|
772
|
+
};
|
|
773
|
+
InvalidRequestError.errorCode = "invalid_request";
|
|
774
|
+
var InvalidClientError = class extends OAuthError {
|
|
775
|
+
};
|
|
776
|
+
InvalidClientError.errorCode = "invalid_client";
|
|
777
|
+
var InvalidGrantError = class extends OAuthError {
|
|
778
|
+
};
|
|
779
|
+
InvalidGrantError.errorCode = "invalid_grant";
|
|
780
|
+
var UnauthorizedClientError = class extends OAuthError {
|
|
781
|
+
};
|
|
782
|
+
UnauthorizedClientError.errorCode = "unauthorized_client";
|
|
783
|
+
var UnsupportedGrantTypeError = class extends OAuthError {
|
|
784
|
+
};
|
|
785
|
+
UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
|
|
786
|
+
var InvalidScopeError = class extends OAuthError {
|
|
787
|
+
};
|
|
788
|
+
InvalidScopeError.errorCode = "invalid_scope";
|
|
789
|
+
var AccessDeniedError = class extends OAuthError {
|
|
790
|
+
};
|
|
791
|
+
AccessDeniedError.errorCode = "access_denied";
|
|
792
|
+
var ServerError = class extends OAuthError {
|
|
793
|
+
};
|
|
794
|
+
ServerError.errorCode = "server_error";
|
|
795
|
+
var TemporarilyUnavailableError = class extends OAuthError {
|
|
796
|
+
};
|
|
797
|
+
TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
|
|
798
|
+
var UnsupportedResponseTypeError = class extends OAuthError {
|
|
799
|
+
};
|
|
800
|
+
UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
|
|
801
|
+
var UnsupportedTokenTypeError = class extends OAuthError {
|
|
802
|
+
};
|
|
803
|
+
UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
|
|
804
|
+
var InvalidTokenError = class extends OAuthError {
|
|
805
|
+
};
|
|
806
|
+
InvalidTokenError.errorCode = "invalid_token";
|
|
807
|
+
var MethodNotAllowedError = class extends OAuthError {
|
|
808
|
+
};
|
|
809
|
+
MethodNotAllowedError.errorCode = "method_not_allowed";
|
|
810
|
+
var TooManyRequestsError = class extends OAuthError {
|
|
811
|
+
};
|
|
812
|
+
TooManyRequestsError.errorCode = "too_many_requests";
|
|
813
|
+
var InvalidClientMetadataError = class extends OAuthError {
|
|
814
|
+
};
|
|
815
|
+
InvalidClientMetadataError.errorCode = "invalid_client_metadata";
|
|
816
|
+
var InsufficientScopeError = class extends OAuthError {
|
|
817
|
+
};
|
|
818
|
+
InsufficientScopeError.errorCode = "insufficient_scope";
|
|
819
|
+
var InvalidTargetError = class extends OAuthError {
|
|
820
|
+
};
|
|
821
|
+
InvalidTargetError.errorCode = "invalid_target";
|
|
822
|
+
var OAUTH_ERRORS = {
|
|
823
|
+
[InvalidRequestError.errorCode]: InvalidRequestError,
|
|
824
|
+
[InvalidClientError.errorCode]: InvalidClientError,
|
|
825
|
+
[InvalidGrantError.errorCode]: InvalidGrantError,
|
|
826
|
+
[UnauthorizedClientError.errorCode]: UnauthorizedClientError,
|
|
827
|
+
[UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
|
|
828
|
+
[InvalidScopeError.errorCode]: InvalidScopeError,
|
|
829
|
+
[AccessDeniedError.errorCode]: AccessDeniedError,
|
|
830
|
+
[ServerError.errorCode]: ServerError,
|
|
831
|
+
[TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
|
|
832
|
+
[UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
|
|
833
|
+
[UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
|
|
834
|
+
[InvalidTokenError.errorCode]: InvalidTokenError,
|
|
835
|
+
[MethodNotAllowedError.errorCode]: MethodNotAllowedError,
|
|
836
|
+
[TooManyRequestsError.errorCode]: TooManyRequestsError,
|
|
837
|
+
[InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
|
|
838
|
+
[InsufficientScopeError.errorCode]: InsufficientScopeError,
|
|
839
|
+
[InvalidTargetError.errorCode]: InvalidTargetError
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
|
|
843
|
+
var UnauthorizedError = class extends Error {
|
|
844
|
+
constructor(message) {
|
|
845
|
+
super(message ?? "Unauthorized");
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
function isClientAuthMethod(method) {
|
|
849
|
+
return ["client_secret_basic", "client_secret_post", "none"].includes(method);
|
|
850
|
+
}
|
|
851
|
+
var AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
|
|
852
|
+
var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
|
|
853
|
+
function selectClientAuthMethod(clientInformation, supportedMethods) {
|
|
854
|
+
const hasClientSecret = clientInformation.client_secret !== void 0;
|
|
855
|
+
if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {
|
|
856
|
+
return clientInformation.token_endpoint_auth_method;
|
|
857
|
+
}
|
|
858
|
+
if (supportedMethods.length === 0) {
|
|
859
|
+
return hasClientSecret ? "client_secret_basic" : "none";
|
|
860
|
+
}
|
|
861
|
+
if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
|
|
862
|
+
return "client_secret_basic";
|
|
863
|
+
}
|
|
864
|
+
if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
|
|
865
|
+
return "client_secret_post";
|
|
866
|
+
}
|
|
867
|
+
if (supportedMethods.includes("none")) {
|
|
868
|
+
return "none";
|
|
869
|
+
}
|
|
870
|
+
return hasClientSecret ? "client_secret_post" : "none";
|
|
871
|
+
}
|
|
872
|
+
function applyClientAuthentication(method, clientInformation, headers, params) {
|
|
873
|
+
const { client_id, client_secret } = clientInformation;
|
|
874
|
+
switch (method) {
|
|
875
|
+
case "client_secret_basic":
|
|
876
|
+
applyBasicAuth(client_id, client_secret, headers);
|
|
877
|
+
return;
|
|
878
|
+
case "client_secret_post":
|
|
879
|
+
applyPostAuth(client_id, client_secret, params);
|
|
880
|
+
return;
|
|
881
|
+
case "none":
|
|
882
|
+
applyPublicAuth(client_id, params);
|
|
883
|
+
return;
|
|
884
|
+
default:
|
|
885
|
+
throw new Error(`Unsupported client authentication method: ${method}`);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
function applyBasicAuth(clientId, clientSecret, headers) {
|
|
889
|
+
if (!clientSecret) {
|
|
890
|
+
throw new Error("client_secret_basic authentication requires a client_secret");
|
|
891
|
+
}
|
|
892
|
+
const credentials = btoa(`${clientId}:${clientSecret}`);
|
|
893
|
+
headers.set("Authorization", `Basic ${credentials}`);
|
|
894
|
+
}
|
|
895
|
+
function applyPostAuth(clientId, clientSecret, params) {
|
|
896
|
+
params.set("client_id", clientId);
|
|
897
|
+
if (clientSecret) {
|
|
898
|
+
params.set("client_secret", clientSecret);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
function applyPublicAuth(clientId, params) {
|
|
902
|
+
params.set("client_id", clientId);
|
|
903
|
+
}
|
|
904
|
+
async function parseErrorResponse(input) {
|
|
905
|
+
const statusCode = input instanceof Response ? input.status : void 0;
|
|
906
|
+
const body = input instanceof Response ? await input.text() : input;
|
|
907
|
+
try {
|
|
908
|
+
const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
|
|
909
|
+
const { error, error_description, error_uri } = result;
|
|
910
|
+
const errorClass = OAUTH_ERRORS[error] || ServerError;
|
|
911
|
+
return new errorClass(error_description || "", error_uri);
|
|
912
|
+
} catch (error) {
|
|
913
|
+
const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
|
|
914
|
+
return new ServerError(errorMessage);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
async function auth(provider, options) {
|
|
918
|
+
try {
|
|
919
|
+
return await authInternal(provider, options);
|
|
920
|
+
} catch (error) {
|
|
921
|
+
if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
|
|
922
|
+
await provider.invalidateCredentials?.("all");
|
|
923
|
+
return await authInternal(provider, options);
|
|
924
|
+
} else if (error instanceof InvalidGrantError) {
|
|
925
|
+
await provider.invalidateCredentials?.("tokens");
|
|
926
|
+
return await authInternal(provider, options);
|
|
927
|
+
}
|
|
928
|
+
throw error;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
|
|
932
|
+
const cachedState = await provider.discoveryState?.();
|
|
933
|
+
let resourceMetadata;
|
|
934
|
+
let authorizationServerUrl;
|
|
935
|
+
let metadata;
|
|
936
|
+
let effectiveResourceMetadataUrl = resourceMetadataUrl;
|
|
937
|
+
if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
|
|
938
|
+
effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
|
|
939
|
+
}
|
|
940
|
+
if (cachedState?.authorizationServerUrl) {
|
|
941
|
+
authorizationServerUrl = cachedState.authorizationServerUrl;
|
|
942
|
+
resourceMetadata = cachedState.resourceMetadata;
|
|
943
|
+
metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
|
|
944
|
+
if (!resourceMetadata) {
|
|
945
|
+
try {
|
|
946
|
+
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
|
|
947
|
+
} catch {
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
|
|
951
|
+
await provider.saveDiscoveryState?.({
|
|
952
|
+
authorizationServerUrl: String(authorizationServerUrl),
|
|
953
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
|
|
954
|
+
resourceMetadata,
|
|
955
|
+
authorizationServerMetadata: metadata
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
} else {
|
|
959
|
+
const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
|
|
960
|
+
authorizationServerUrl = serverInfo.authorizationServerUrl;
|
|
961
|
+
metadata = serverInfo.authorizationServerMetadata;
|
|
962
|
+
resourceMetadata = serverInfo.resourceMetadata;
|
|
963
|
+
await provider.saveDiscoveryState?.({
|
|
964
|
+
authorizationServerUrl: String(authorizationServerUrl),
|
|
965
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
|
|
966
|
+
resourceMetadata,
|
|
967
|
+
authorizationServerMetadata: metadata
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
|
|
971
|
+
const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
|
|
972
|
+
let clientInformation = await Promise.resolve(provider.clientInformation());
|
|
973
|
+
if (!clientInformation) {
|
|
974
|
+
if (authorizationCode !== void 0) {
|
|
975
|
+
throw new Error("Existing OAuth client information is required when exchanging an authorization code");
|
|
976
|
+
}
|
|
977
|
+
const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
|
|
978
|
+
const clientMetadataUrl = provider.clientMetadataUrl;
|
|
979
|
+
if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
|
|
980
|
+
throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
|
|
981
|
+
}
|
|
982
|
+
const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
|
|
983
|
+
if (shouldUseUrlBasedClientId) {
|
|
984
|
+
clientInformation = {
|
|
985
|
+
client_id: clientMetadataUrl
|
|
986
|
+
};
|
|
987
|
+
await provider.saveClientInformation?.(clientInformation);
|
|
988
|
+
} else {
|
|
989
|
+
if (!provider.saveClientInformation) {
|
|
990
|
+
throw new Error("OAuth client information must be saveable for dynamic registration");
|
|
991
|
+
}
|
|
992
|
+
const fullInformation = await registerClient(authorizationServerUrl, {
|
|
993
|
+
metadata,
|
|
994
|
+
clientMetadata: provider.clientMetadata,
|
|
995
|
+
scope: resolvedScope,
|
|
996
|
+
fetchFn
|
|
997
|
+
});
|
|
998
|
+
await provider.saveClientInformation(fullInformation);
|
|
999
|
+
clientInformation = fullInformation;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
const nonInteractiveFlow = !provider.redirectUrl;
|
|
1003
|
+
if (authorizationCode !== void 0 || nonInteractiveFlow) {
|
|
1004
|
+
const tokens2 = await fetchToken(provider, authorizationServerUrl, {
|
|
1005
|
+
metadata,
|
|
1006
|
+
resource,
|
|
1007
|
+
authorizationCode,
|
|
1008
|
+
fetchFn
|
|
1009
|
+
});
|
|
1010
|
+
await provider.saveTokens(tokens2);
|
|
1011
|
+
return "AUTHORIZED";
|
|
1012
|
+
}
|
|
1013
|
+
const tokens = await provider.tokens();
|
|
1014
|
+
if (tokens?.refresh_token) {
|
|
1015
|
+
try {
|
|
1016
|
+
const newTokens = await refreshAuthorization(authorizationServerUrl, {
|
|
1017
|
+
metadata,
|
|
1018
|
+
clientInformation,
|
|
1019
|
+
refreshToken: tokens.refresh_token,
|
|
1020
|
+
resource,
|
|
1021
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
1022
|
+
fetchFn
|
|
1023
|
+
});
|
|
1024
|
+
await provider.saveTokens(newTokens);
|
|
1025
|
+
return "AUTHORIZED";
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
if (!(error instanceof OAuthError) || error instanceof ServerError) {
|
|
1028
|
+
} else {
|
|
1029
|
+
throw error;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
const state = provider.state ? await provider.state() : void 0;
|
|
1034
|
+
const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
|
|
1035
|
+
metadata,
|
|
1036
|
+
clientInformation,
|
|
1037
|
+
state,
|
|
1038
|
+
redirectUrl: provider.redirectUrl,
|
|
1039
|
+
scope: resolvedScope,
|
|
1040
|
+
resource
|
|
1041
|
+
});
|
|
1042
|
+
await provider.saveCodeVerifier(codeVerifier);
|
|
1043
|
+
await provider.redirectToAuthorization(authorizationUrl);
|
|
1044
|
+
return "REDIRECT";
|
|
1045
|
+
}
|
|
1046
|
+
function isHttpsUrl(value) {
|
|
1047
|
+
if (!value)
|
|
1048
|
+
return false;
|
|
1049
|
+
try {
|
|
1050
|
+
const url2 = new URL(value);
|
|
1051
|
+
return url2.protocol === "https:" && url2.pathname !== "/";
|
|
1052
|
+
} catch {
|
|
1053
|
+
return false;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
|
|
1057
|
+
const defaultResource = resourceUrlFromServerUrl(serverUrl);
|
|
1058
|
+
if (provider.validateResourceURL) {
|
|
1059
|
+
return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
|
|
1060
|
+
}
|
|
1061
|
+
if (!resourceMetadata) {
|
|
1062
|
+
return void 0;
|
|
1063
|
+
}
|
|
1064
|
+
if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
|
|
1065
|
+
throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
|
|
1066
|
+
}
|
|
1067
|
+
return new URL(resourceMetadata.resource);
|
|
1068
|
+
}
|
|
1069
|
+
function extractWWWAuthenticateParams(res) {
|
|
1070
|
+
const authenticateHeader = res.headers.get("WWW-Authenticate");
|
|
1071
|
+
if (!authenticateHeader) {
|
|
1072
|
+
return {};
|
|
1073
|
+
}
|
|
1074
|
+
const [type, scheme] = authenticateHeader.split(" ");
|
|
1075
|
+
if (type.toLowerCase() !== "bearer" || !scheme) {
|
|
1076
|
+
return {};
|
|
1077
|
+
}
|
|
1078
|
+
const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
|
|
1079
|
+
let resourceMetadataUrl;
|
|
1080
|
+
if (resourceMetadataMatch) {
|
|
1081
|
+
try {
|
|
1082
|
+
resourceMetadataUrl = new URL(resourceMetadataMatch);
|
|
1083
|
+
} catch {
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
|
|
1087
|
+
const error = extractFieldFromWwwAuth(res, "error") || void 0;
|
|
1088
|
+
return {
|
|
1089
|
+
resourceMetadataUrl,
|
|
1090
|
+
scope,
|
|
1091
|
+
error
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
function extractFieldFromWwwAuth(response, fieldName) {
|
|
1095
|
+
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
1096
|
+
if (!wwwAuthHeader) {
|
|
1097
|
+
return null;
|
|
1098
|
+
}
|
|
1099
|
+
const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
|
|
1100
|
+
const match = wwwAuthHeader.match(pattern);
|
|
1101
|
+
if (match) {
|
|
1102
|
+
return match[1] || match[2];
|
|
1103
|
+
}
|
|
1104
|
+
return null;
|
|
1105
|
+
}
|
|
1106
|
+
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
|
|
1107
|
+
const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
|
|
1108
|
+
protocolVersion: opts?.protocolVersion,
|
|
1109
|
+
metadataUrl: opts?.resourceMetadataUrl
|
|
1110
|
+
});
|
|
1111
|
+
if (!response || response.status === 404) {
|
|
1112
|
+
await response?.body?.cancel();
|
|
1113
|
+
throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
|
|
1114
|
+
}
|
|
1115
|
+
if (!response.ok) {
|
|
1116
|
+
await response.body?.cancel();
|
|
1117
|
+
throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
|
|
1118
|
+
}
|
|
1119
|
+
return OAuthProtectedResourceMetadataSchema.parse(await response.json());
|
|
1120
|
+
}
|
|
1121
|
+
async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
|
|
1122
|
+
try {
|
|
1123
|
+
return await fetchFn(url2, { headers });
|
|
1124
|
+
} catch (error) {
|
|
1125
|
+
if (error instanceof TypeError) {
|
|
1126
|
+
if (headers) {
|
|
1127
|
+
return fetchWithCorsRetry(url2, void 0, fetchFn);
|
|
1128
|
+
} else {
|
|
1129
|
+
return void 0;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
throw error;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
|
|
1136
|
+
if (pathname.endsWith("/")) {
|
|
1137
|
+
pathname = pathname.slice(0, -1);
|
|
1138
|
+
}
|
|
1139
|
+
return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
|
|
1140
|
+
}
|
|
1141
|
+
async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
|
|
1142
|
+
const headers = {
|
|
1143
|
+
"MCP-Protocol-Version": protocolVersion
|
|
1144
|
+
};
|
|
1145
|
+
return await fetchWithCorsRetry(url2, headers, fetchFn);
|
|
1146
|
+
}
|
|
1147
|
+
function shouldAttemptFallback(response, pathname) {
|
|
1148
|
+
return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
|
|
1149
|
+
}
|
|
1150
|
+
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
|
|
1151
|
+
const issuer = new URL(serverUrl);
|
|
1152
|
+
const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
|
|
1153
|
+
let url2;
|
|
1154
|
+
if (opts?.metadataUrl) {
|
|
1155
|
+
url2 = new URL(opts.metadataUrl);
|
|
1156
|
+
} else {
|
|
1157
|
+
const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
|
|
1158
|
+
url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
|
|
1159
|
+
url2.search = issuer.search;
|
|
1160
|
+
}
|
|
1161
|
+
let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
|
|
1162
|
+
if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
|
|
1163
|
+
const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
|
|
1164
|
+
response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
|
|
1165
|
+
}
|
|
1166
|
+
return response;
|
|
1167
|
+
}
|
|
1168
|
+
function buildDiscoveryUrls(authorizationServerUrl) {
|
|
1169
|
+
const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
|
|
1170
|
+
const hasPath = url2.pathname !== "/";
|
|
1171
|
+
const urlsToTry = [];
|
|
1172
|
+
if (!hasPath) {
|
|
1173
|
+
urlsToTry.push({
|
|
1174
|
+
url: new URL("/.well-known/oauth-authorization-server", url2.origin),
|
|
1175
|
+
type: "oauth"
|
|
1176
|
+
});
|
|
1177
|
+
urlsToTry.push({
|
|
1178
|
+
url: new URL(`/.well-known/openid-configuration`, url2.origin),
|
|
1179
|
+
type: "oidc"
|
|
1180
|
+
});
|
|
1181
|
+
return urlsToTry;
|
|
1182
|
+
}
|
|
1183
|
+
let pathname = url2.pathname;
|
|
1184
|
+
if (pathname.endsWith("/")) {
|
|
1185
|
+
pathname = pathname.slice(0, -1);
|
|
1186
|
+
}
|
|
1187
|
+
urlsToTry.push({
|
|
1188
|
+
url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
|
|
1189
|
+
type: "oauth"
|
|
1190
|
+
});
|
|
1191
|
+
urlsToTry.push({
|
|
1192
|
+
url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
|
|
1193
|
+
type: "oidc"
|
|
1194
|
+
});
|
|
1195
|
+
urlsToTry.push({
|
|
1196
|
+
url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
|
|
1197
|
+
type: "oidc"
|
|
1198
|
+
});
|
|
1199
|
+
return urlsToTry;
|
|
1200
|
+
}
|
|
1201
|
+
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
|
|
1202
|
+
const headers = {
|
|
1203
|
+
"MCP-Protocol-Version": protocolVersion,
|
|
1204
|
+
Accept: "application/json"
|
|
1205
|
+
};
|
|
1206
|
+
const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
|
|
1207
|
+
for (const { url: endpointUrl, type } of urlsToTry) {
|
|
1208
|
+
const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
|
|
1209
|
+
if (!response) {
|
|
1210
|
+
continue;
|
|
1211
|
+
}
|
|
1212
|
+
if (!response.ok) {
|
|
1213
|
+
await response.body?.cancel();
|
|
1214
|
+
if (response.status >= 400 && response.status < 500) {
|
|
1215
|
+
continue;
|
|
1216
|
+
}
|
|
1217
|
+
throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
|
|
1218
|
+
}
|
|
1219
|
+
if (type === "oauth") {
|
|
1220
|
+
return OAuthMetadataSchema.parse(await response.json());
|
|
1221
|
+
} else {
|
|
1222
|
+
return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
return void 0;
|
|
1226
|
+
}
|
|
1227
|
+
async function discoverOAuthServerInfo(serverUrl, opts) {
|
|
1228
|
+
let resourceMetadata;
|
|
1229
|
+
let authorizationServerUrl;
|
|
1230
|
+
try {
|
|
1231
|
+
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
|
|
1232
|
+
if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
|
|
1233
|
+
authorizationServerUrl = resourceMetadata.authorization_servers[0];
|
|
1234
|
+
}
|
|
1235
|
+
} catch {
|
|
1236
|
+
}
|
|
1237
|
+
if (!authorizationServerUrl) {
|
|
1238
|
+
authorizationServerUrl = String(new URL("/", serverUrl));
|
|
1239
|
+
}
|
|
1240
|
+
const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
|
|
1241
|
+
return {
|
|
1242
|
+
authorizationServerUrl,
|
|
1243
|
+
authorizationServerMetadata,
|
|
1244
|
+
resourceMetadata
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
|
|
1248
|
+
let authorizationUrl;
|
|
1249
|
+
if (metadata) {
|
|
1250
|
+
authorizationUrl = new URL(metadata.authorization_endpoint);
|
|
1251
|
+
if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
|
|
1252
|
+
throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
|
|
1253
|
+
}
|
|
1254
|
+
if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
|
|
1255
|
+
throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
|
|
1256
|
+
}
|
|
1257
|
+
} else {
|
|
1258
|
+
authorizationUrl = new URL("/authorize", authorizationServerUrl);
|
|
1259
|
+
}
|
|
1260
|
+
const challenge = await pkceChallenge();
|
|
1261
|
+
const codeVerifier = challenge.code_verifier;
|
|
1262
|
+
const codeChallenge = challenge.code_challenge;
|
|
1263
|
+
authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
|
|
1264
|
+
authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
|
|
1265
|
+
authorizationUrl.searchParams.set("code_challenge", codeChallenge);
|
|
1266
|
+
authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
|
|
1267
|
+
authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
|
|
1268
|
+
if (state) {
|
|
1269
|
+
authorizationUrl.searchParams.set("state", state);
|
|
1270
|
+
}
|
|
1271
|
+
if (scope) {
|
|
1272
|
+
authorizationUrl.searchParams.set("scope", scope);
|
|
1273
|
+
}
|
|
1274
|
+
if (scope?.includes("offline_access")) {
|
|
1275
|
+
authorizationUrl.searchParams.append("prompt", "consent");
|
|
1276
|
+
}
|
|
1277
|
+
if (resource) {
|
|
1278
|
+
authorizationUrl.searchParams.set("resource", resource.href);
|
|
1279
|
+
}
|
|
1280
|
+
return { authorizationUrl, codeVerifier };
|
|
1281
|
+
}
|
|
1282
|
+
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
|
|
1283
|
+
return new URLSearchParams({
|
|
1284
|
+
grant_type: "authorization_code",
|
|
1285
|
+
code: authorizationCode,
|
|
1286
|
+
code_verifier: codeVerifier,
|
|
1287
|
+
redirect_uri: String(redirectUri)
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
|
|
1291
|
+
const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
|
|
1292
|
+
const headers = new Headers({
|
|
1293
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1294
|
+
Accept: "application/json"
|
|
1295
|
+
});
|
|
1296
|
+
if (resource) {
|
|
1297
|
+
tokenRequestParams.set("resource", resource.href);
|
|
1298
|
+
}
|
|
1299
|
+
if (addClientAuthentication) {
|
|
1300
|
+
await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
|
|
1301
|
+
} else if (clientInformation) {
|
|
1302
|
+
const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
|
|
1303
|
+
const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
|
|
1304
|
+
applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
|
|
1305
|
+
}
|
|
1306
|
+
const response = await (fetchFn ?? fetch)(tokenUrl, {
|
|
1307
|
+
method: "POST",
|
|
1308
|
+
headers,
|
|
1309
|
+
body: tokenRequestParams
|
|
1310
|
+
});
|
|
1311
|
+
if (!response.ok) {
|
|
1312
|
+
throw await parseErrorResponse(response);
|
|
1313
|
+
}
|
|
1314
|
+
return OAuthTokensSchema.parse(await response.json());
|
|
1315
|
+
}
|
|
1316
|
+
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
|
|
1317
|
+
const tokenRequestParams = new URLSearchParams({
|
|
1318
|
+
grant_type: "refresh_token",
|
|
1319
|
+
refresh_token: refreshToken
|
|
1320
|
+
});
|
|
1321
|
+
const tokens = await executeTokenRequest(authorizationServerUrl, {
|
|
1322
|
+
metadata,
|
|
1323
|
+
tokenRequestParams,
|
|
1324
|
+
clientInformation,
|
|
1325
|
+
addClientAuthentication,
|
|
1326
|
+
resource,
|
|
1327
|
+
fetchFn
|
|
1328
|
+
});
|
|
1329
|
+
return { refresh_token: refreshToken, ...tokens };
|
|
1330
|
+
}
|
|
1331
|
+
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
|
|
1332
|
+
const scope = provider.clientMetadata.scope;
|
|
1333
|
+
let tokenRequestParams;
|
|
1334
|
+
if (provider.prepareTokenRequest) {
|
|
1335
|
+
tokenRequestParams = await provider.prepareTokenRequest(scope);
|
|
1336
|
+
}
|
|
1337
|
+
if (!tokenRequestParams) {
|
|
1338
|
+
if (!authorizationCode) {
|
|
1339
|
+
throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
|
|
1340
|
+
}
|
|
1341
|
+
if (!provider.redirectUrl) {
|
|
1342
|
+
throw new Error("redirectUrl is required for authorization_code flow");
|
|
1343
|
+
}
|
|
1344
|
+
const codeVerifier = await provider.codeVerifier();
|
|
1345
|
+
tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
|
|
1346
|
+
}
|
|
1347
|
+
const clientInformation = await provider.clientInformation();
|
|
1348
|
+
return executeTokenRequest(authorizationServerUrl, {
|
|
1349
|
+
metadata,
|
|
1350
|
+
tokenRequestParams,
|
|
1351
|
+
clientInformation: clientInformation ?? void 0,
|
|
1352
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
1353
|
+
resource,
|
|
1354
|
+
fetchFn
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
|
|
1358
|
+
let registrationUrl;
|
|
1359
|
+
if (metadata) {
|
|
1360
|
+
if (!metadata.registration_endpoint) {
|
|
1361
|
+
throw new Error("Incompatible auth server: does not support dynamic client registration");
|
|
1362
|
+
}
|
|
1363
|
+
registrationUrl = new URL(metadata.registration_endpoint);
|
|
1364
|
+
} else {
|
|
1365
|
+
registrationUrl = new URL("/register", authorizationServerUrl);
|
|
1366
|
+
}
|
|
1367
|
+
const response = await (fetchFn ?? fetch)(registrationUrl, {
|
|
1368
|
+
method: "POST",
|
|
1369
|
+
headers: {
|
|
1370
|
+
"Content-Type": "application/json"
|
|
1371
|
+
},
|
|
1372
|
+
body: JSON.stringify({
|
|
1373
|
+
...clientMetadata,
|
|
1374
|
+
...scope !== void 0 ? { scope } : {}
|
|
1375
|
+
})
|
|
1376
|
+
});
|
|
1377
|
+
if (!response.ok) {
|
|
1378
|
+
throw await parseErrorResponse(response);
|
|
1379
|
+
}
|
|
1380
|
+
return OAuthClientInformationFullSchema.parse(await response.json());
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
|
|
1384
|
+
var SseError = class extends Error {
|
|
1385
|
+
constructor(code, message, event) {
|
|
1386
|
+
super(`SSE error: ${message}`);
|
|
1387
|
+
this.code = code;
|
|
1388
|
+
this.event = event;
|
|
1389
|
+
}
|
|
1390
|
+
};
|
|
1391
|
+
var SSEClientTransport = class {
|
|
1392
|
+
constructor(url2, opts) {
|
|
1393
|
+
this._url = url2;
|
|
1394
|
+
this._resourceMetadataUrl = void 0;
|
|
1395
|
+
this._scope = void 0;
|
|
1396
|
+
this._eventSourceInit = opts?.eventSourceInit;
|
|
1397
|
+
this._requestInit = opts?.requestInit;
|
|
1398
|
+
this._authProvider = opts?.authProvider;
|
|
1399
|
+
this._fetch = opts?.fetch;
|
|
1400
|
+
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
1401
|
+
}
|
|
1402
|
+
async _authThenStart() {
|
|
1403
|
+
if (!this._authProvider) {
|
|
1404
|
+
throw new UnauthorizedError("No auth provider");
|
|
1405
|
+
}
|
|
1406
|
+
let result;
|
|
1407
|
+
try {
|
|
1408
|
+
result = await auth(this._authProvider, {
|
|
1409
|
+
serverUrl: this._url,
|
|
1410
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1411
|
+
scope: this._scope,
|
|
1412
|
+
fetchFn: this._fetchWithInit
|
|
1413
|
+
});
|
|
1414
|
+
} catch (error) {
|
|
1415
|
+
this.onerror?.(error);
|
|
1416
|
+
throw error;
|
|
1417
|
+
}
|
|
1418
|
+
if (result !== "AUTHORIZED") {
|
|
1419
|
+
throw new UnauthorizedError();
|
|
1420
|
+
}
|
|
1421
|
+
return await this._startOrAuth();
|
|
1422
|
+
}
|
|
1423
|
+
async _commonHeaders() {
|
|
1424
|
+
const headers = {};
|
|
1425
|
+
if (this._authProvider) {
|
|
1426
|
+
const tokens = await this._authProvider.tokens();
|
|
1427
|
+
if (tokens) {
|
|
1428
|
+
headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
if (this._protocolVersion) {
|
|
1432
|
+
headers["mcp-protocol-version"] = this._protocolVersion;
|
|
1433
|
+
}
|
|
1434
|
+
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
1435
|
+
return new Headers({
|
|
1436
|
+
...headers,
|
|
1437
|
+
...extraHeaders
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
_startOrAuth() {
|
|
1441
|
+
const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
|
|
1442
|
+
return new Promise((resolve, reject) => {
|
|
1443
|
+
this._eventSource = new EventSource(this._url.href, {
|
|
1444
|
+
...this._eventSourceInit,
|
|
1445
|
+
fetch: async (url2, init) => {
|
|
1446
|
+
const headers = await this._commonHeaders();
|
|
1447
|
+
headers.set("Accept", "text/event-stream");
|
|
1448
|
+
const response = await fetchImpl(url2, {
|
|
1449
|
+
...init,
|
|
1450
|
+
headers
|
|
1451
|
+
});
|
|
1452
|
+
if (response.status === 401 && response.headers.has("www-authenticate")) {
|
|
1453
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
1454
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
1455
|
+
this._scope = scope;
|
|
1456
|
+
}
|
|
1457
|
+
return response;
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
this._abortController = new AbortController();
|
|
1461
|
+
this._eventSource.onerror = (event) => {
|
|
1462
|
+
if (event.code === 401 && this._authProvider) {
|
|
1463
|
+
this._authThenStart().then(resolve, reject);
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
const error = new SseError(event.code, event.message, event);
|
|
1467
|
+
reject(error);
|
|
1468
|
+
this.onerror?.(error);
|
|
1469
|
+
};
|
|
1470
|
+
this._eventSource.onopen = () => {
|
|
1471
|
+
};
|
|
1472
|
+
this._eventSource.addEventListener("endpoint", (event) => {
|
|
1473
|
+
const messageEvent = event;
|
|
1474
|
+
try {
|
|
1475
|
+
this._endpoint = new URL(messageEvent.data, this._url);
|
|
1476
|
+
if (this._endpoint.origin !== this._url.origin) {
|
|
1477
|
+
throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
|
|
1478
|
+
}
|
|
1479
|
+
} catch (error) {
|
|
1480
|
+
reject(error);
|
|
1481
|
+
this.onerror?.(error);
|
|
1482
|
+
void this.close();
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
resolve();
|
|
1486
|
+
});
|
|
1487
|
+
this._eventSource.onmessage = (event) => {
|
|
1488
|
+
const messageEvent = event;
|
|
1489
|
+
let message;
|
|
1490
|
+
try {
|
|
1491
|
+
message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
|
|
1492
|
+
} catch (error) {
|
|
1493
|
+
this.onerror?.(error);
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
this.onmessage?.(message);
|
|
1497
|
+
};
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
async start() {
|
|
1501
|
+
if (this._eventSource) {
|
|
1502
|
+
throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
1503
|
+
}
|
|
1504
|
+
return await this._startOrAuth();
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
1508
|
+
*/
|
|
1509
|
+
async finishAuth(authorizationCode) {
|
|
1510
|
+
if (!this._authProvider) {
|
|
1511
|
+
throw new UnauthorizedError("No auth provider");
|
|
1512
|
+
}
|
|
1513
|
+
const result = await auth(this._authProvider, {
|
|
1514
|
+
serverUrl: this._url,
|
|
1515
|
+
authorizationCode,
|
|
1516
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1517
|
+
scope: this._scope,
|
|
1518
|
+
fetchFn: this._fetchWithInit
|
|
1519
|
+
});
|
|
1520
|
+
if (result !== "AUTHORIZED") {
|
|
1521
|
+
throw new UnauthorizedError("Failed to authorize");
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
async close() {
|
|
1525
|
+
this._abortController?.abort();
|
|
1526
|
+
this._eventSource?.close();
|
|
1527
|
+
this.onclose?.();
|
|
1528
|
+
}
|
|
1529
|
+
async send(message) {
|
|
1530
|
+
if (!this._endpoint) {
|
|
1531
|
+
throw new Error("Not connected");
|
|
1532
|
+
}
|
|
1533
|
+
try {
|
|
1534
|
+
const headers = await this._commonHeaders();
|
|
1535
|
+
headers.set("content-type", "application/json");
|
|
1536
|
+
const init = {
|
|
1537
|
+
...this._requestInit,
|
|
1538
|
+
method: "POST",
|
|
1539
|
+
headers,
|
|
1540
|
+
body: JSON.stringify(message),
|
|
1541
|
+
signal: this._abortController?.signal
|
|
1542
|
+
};
|
|
1543
|
+
const response = await (this._fetch ?? fetch)(this._endpoint, init);
|
|
1544
|
+
if (!response.ok) {
|
|
1545
|
+
const text = await response.text().catch(() => null);
|
|
1546
|
+
if (response.status === 401 && this._authProvider) {
|
|
1547
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
1548
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
1549
|
+
this._scope = scope;
|
|
1550
|
+
const result = await auth(this._authProvider, {
|
|
1551
|
+
serverUrl: this._url,
|
|
1552
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1553
|
+
scope: this._scope,
|
|
1554
|
+
fetchFn: this._fetchWithInit
|
|
1555
|
+
});
|
|
1556
|
+
if (result !== "AUTHORIZED") {
|
|
1557
|
+
throw new UnauthorizedError();
|
|
1558
|
+
}
|
|
1559
|
+
return this.send(message);
|
|
1560
|
+
}
|
|
1561
|
+
throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
|
|
1562
|
+
}
|
|
1563
|
+
await response.body?.cancel();
|
|
1564
|
+
} catch (error) {
|
|
1565
|
+
this.onerror?.(error);
|
|
1566
|
+
throw error;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
setProtocolVersion(version) {
|
|
1570
|
+
this._protocolVersion = version;
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1573
|
+
|
|
1574
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
|
|
1575
|
+
init_esm_shims();
|
|
1576
|
+
|
|
1577
|
+
// node_modules/eventsource-parser/dist/stream.js
|
|
1578
|
+
init_esm_shims();
|
|
1579
|
+
var EventSourceParserStream = class extends TransformStream {
|
|
1580
|
+
constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
|
|
1581
|
+
let parser;
|
|
1582
|
+
super({
|
|
1583
|
+
start(controller) {
|
|
1584
|
+
parser = createParser({
|
|
1585
|
+
onEvent: (event) => {
|
|
1586
|
+
controller.enqueue(event);
|
|
1587
|
+
},
|
|
1588
|
+
onError(error) {
|
|
1589
|
+
typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
|
|
1590
|
+
},
|
|
1591
|
+
onRetry,
|
|
1592
|
+
onComment,
|
|
1593
|
+
maxBufferSize
|
|
1594
|
+
});
|
|
1595
|
+
},
|
|
1596
|
+
transform(chunk) {
|
|
1597
|
+
parser.feed(chunk);
|
|
1598
|
+
}
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
|
|
1603
|
+
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
|
|
1604
|
+
var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
|
|
1605
|
+
initialReconnectionDelay: 1e3,
|
|
1606
|
+
maxReconnectionDelay: 3e4,
|
|
1607
|
+
reconnectionDelayGrowFactor: 1.5,
|
|
1608
|
+
maxRetries: 2
|
|
1609
|
+
};
|
|
1610
|
+
var StreamableHTTPError = class extends Error {
|
|
1611
|
+
constructor(code, message) {
|
|
1612
|
+
super(`Streamable HTTP error: ${message}`);
|
|
1613
|
+
this.code = code;
|
|
1614
|
+
}
|
|
1615
|
+
};
|
|
1616
|
+
var StreamableHTTPClientTransport = class {
|
|
1617
|
+
constructor(url2, opts) {
|
|
1618
|
+
this._hasCompletedAuthFlow = false;
|
|
1619
|
+
this._url = url2;
|
|
1620
|
+
this._resourceMetadataUrl = void 0;
|
|
1621
|
+
this._scope = void 0;
|
|
1622
|
+
this._requestInit = opts?.requestInit;
|
|
1623
|
+
this._authProvider = opts?.authProvider;
|
|
1624
|
+
this._fetch = opts?.fetch;
|
|
1625
|
+
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
1626
|
+
this._sessionId = opts?.sessionId;
|
|
1627
|
+
this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
|
|
1628
|
+
}
|
|
1629
|
+
async _authThenStart() {
|
|
1630
|
+
if (!this._authProvider) {
|
|
1631
|
+
throw new UnauthorizedError("No auth provider");
|
|
1632
|
+
}
|
|
1633
|
+
let result;
|
|
1634
|
+
try {
|
|
1635
|
+
result = await auth(this._authProvider, {
|
|
1636
|
+
serverUrl: this._url,
|
|
1637
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1638
|
+
scope: this._scope,
|
|
1639
|
+
fetchFn: this._fetchWithInit
|
|
1640
|
+
});
|
|
1641
|
+
} catch (error) {
|
|
1642
|
+
this.onerror?.(error);
|
|
1643
|
+
throw error;
|
|
1644
|
+
}
|
|
1645
|
+
if (result !== "AUTHORIZED") {
|
|
1646
|
+
throw new UnauthorizedError();
|
|
1647
|
+
}
|
|
1648
|
+
return await this._startOrAuthSse({ resumptionToken: void 0 });
|
|
1649
|
+
}
|
|
1650
|
+
async _commonHeaders() {
|
|
1651
|
+
const headers = {};
|
|
1652
|
+
if (this._authProvider) {
|
|
1653
|
+
const tokens = await this._authProvider.tokens();
|
|
1654
|
+
if (tokens) {
|
|
1655
|
+
headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
if (this._sessionId) {
|
|
1659
|
+
headers["mcp-session-id"] = this._sessionId;
|
|
1660
|
+
}
|
|
1661
|
+
if (this._protocolVersion) {
|
|
1662
|
+
headers["mcp-protocol-version"] = this._protocolVersion;
|
|
1663
|
+
}
|
|
1664
|
+
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
1665
|
+
return new Headers({
|
|
1666
|
+
...headers,
|
|
1667
|
+
...extraHeaders
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
async _startOrAuthSse(options) {
|
|
1671
|
+
const { resumptionToken } = options;
|
|
1672
|
+
try {
|
|
1673
|
+
const headers = await this._commonHeaders();
|
|
1674
|
+
headers.set("Accept", "text/event-stream");
|
|
1675
|
+
if (resumptionToken) {
|
|
1676
|
+
headers.set("last-event-id", resumptionToken);
|
|
1677
|
+
}
|
|
1678
|
+
const response = await (this._fetch ?? fetch)(this._url, {
|
|
1679
|
+
method: "GET",
|
|
1680
|
+
headers,
|
|
1681
|
+
signal: this._abortController?.signal
|
|
1682
|
+
});
|
|
1683
|
+
if (!response.ok) {
|
|
1684
|
+
await response.body?.cancel();
|
|
1685
|
+
if (response.status === 401 && this._authProvider) {
|
|
1686
|
+
return await this._authThenStart();
|
|
1687
|
+
}
|
|
1688
|
+
if (response.status === 405) {
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
|
|
1692
|
+
}
|
|
1693
|
+
this._handleSseStream(response.body, options, true);
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
this.onerror?.(error);
|
|
1696
|
+
throw error;
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* Calculates the next reconnection delay using backoff algorithm
|
|
1701
|
+
*
|
|
1702
|
+
* @param attempt Current reconnection attempt count for the specific stream
|
|
1703
|
+
* @returns Time to wait in milliseconds before next reconnection attempt
|
|
1704
|
+
*/
|
|
1705
|
+
_getNextReconnectionDelay(attempt) {
|
|
1706
|
+
if (this._serverRetryMs !== void 0) {
|
|
1707
|
+
return this._serverRetryMs;
|
|
1708
|
+
}
|
|
1709
|
+
const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
|
|
1710
|
+
const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
|
|
1711
|
+
const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
|
|
1712
|
+
return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
|
|
1713
|
+
}
|
|
1714
|
+
/**
|
|
1715
|
+
* Schedule a reconnection attempt using server-provided retry interval or backoff
|
|
1716
|
+
*
|
|
1717
|
+
* @param lastEventId The ID of the last received event for resumability
|
|
1718
|
+
* @param attemptCount Current reconnection attempt count for this specific stream
|
|
1719
|
+
*/
|
|
1720
|
+
_scheduleReconnection(options, attemptCount = 0) {
|
|
1721
|
+
const maxRetries = this._reconnectionOptions.maxRetries;
|
|
1722
|
+
if (attemptCount >= maxRetries) {
|
|
1723
|
+
this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1726
|
+
const delay = this._getNextReconnectionDelay(attemptCount);
|
|
1727
|
+
this._reconnectionTimeout = setTimeout(() => {
|
|
1728
|
+
this._startOrAuthSse(options).catch((error) => {
|
|
1729
|
+
this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
|
|
1730
|
+
this._scheduleReconnection(options, attemptCount + 1);
|
|
1731
|
+
});
|
|
1732
|
+
}, delay);
|
|
1733
|
+
}
|
|
1734
|
+
_handleSseStream(stream, options, isReconnectable) {
|
|
1735
|
+
if (!stream) {
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
const { onresumptiontoken, replayMessageId } = options;
|
|
1739
|
+
let lastEventId;
|
|
1740
|
+
let hasPrimingEvent = false;
|
|
1741
|
+
let receivedResponse = false;
|
|
1742
|
+
const processStream = async () => {
|
|
1743
|
+
try {
|
|
1744
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
|
|
1745
|
+
onRetry: (retryMs) => {
|
|
1746
|
+
this._serverRetryMs = retryMs;
|
|
1747
|
+
}
|
|
1748
|
+
})).getReader();
|
|
1749
|
+
while (true) {
|
|
1750
|
+
const { value: event, done } = await reader.read();
|
|
1751
|
+
if (done) {
|
|
1752
|
+
break;
|
|
1753
|
+
}
|
|
1754
|
+
if (event.id) {
|
|
1755
|
+
lastEventId = event.id;
|
|
1756
|
+
hasPrimingEvent = true;
|
|
1757
|
+
onresumptiontoken?.(event.id);
|
|
1758
|
+
}
|
|
1759
|
+
if (!event.data) {
|
|
1760
|
+
continue;
|
|
1761
|
+
}
|
|
1762
|
+
if (!event.event || event.event === "message") {
|
|
1763
|
+
try {
|
|
1764
|
+
const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
|
|
1765
|
+
if (isJSONRPCResultResponse(message)) {
|
|
1766
|
+
receivedResponse = true;
|
|
1767
|
+
if (replayMessageId !== void 0) {
|
|
1768
|
+
message.id = replayMessageId;
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
this.onmessage?.(message);
|
|
1772
|
+
} catch (error) {
|
|
1773
|
+
this.onerror?.(error);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
const canResume = isReconnectable || hasPrimingEvent;
|
|
1778
|
+
const needsReconnect = canResume && !receivedResponse;
|
|
1779
|
+
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
|
|
1780
|
+
this._scheduleReconnection({
|
|
1781
|
+
resumptionToken: lastEventId,
|
|
1782
|
+
onresumptiontoken,
|
|
1783
|
+
replayMessageId
|
|
1784
|
+
}, 0);
|
|
1785
|
+
}
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
|
|
1788
|
+
const canResume = isReconnectable || hasPrimingEvent;
|
|
1789
|
+
const needsReconnect = canResume && !receivedResponse;
|
|
1790
|
+
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
|
|
1791
|
+
try {
|
|
1792
|
+
this._scheduleReconnection({
|
|
1793
|
+
resumptionToken: lastEventId,
|
|
1794
|
+
onresumptiontoken,
|
|
1795
|
+
replayMessageId
|
|
1796
|
+
}, 0);
|
|
1797
|
+
} catch (error2) {
|
|
1798
|
+
this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
};
|
|
1803
|
+
processStream();
|
|
1804
|
+
}
|
|
1805
|
+
async start() {
|
|
1806
|
+
if (this._abortController) {
|
|
1807
|
+
throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
1808
|
+
}
|
|
1809
|
+
this._abortController = new AbortController();
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
1813
|
+
*/
|
|
1814
|
+
async finishAuth(authorizationCode) {
|
|
1815
|
+
if (!this._authProvider) {
|
|
1816
|
+
throw new UnauthorizedError("No auth provider");
|
|
1817
|
+
}
|
|
1818
|
+
const result = await auth(this._authProvider, {
|
|
1819
|
+
serverUrl: this._url,
|
|
1820
|
+
authorizationCode,
|
|
1821
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1822
|
+
scope: this._scope,
|
|
1823
|
+
fetchFn: this._fetchWithInit
|
|
1824
|
+
});
|
|
1825
|
+
if (result !== "AUTHORIZED") {
|
|
1826
|
+
throw new UnauthorizedError("Failed to authorize");
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
async close() {
|
|
1830
|
+
if (this._reconnectionTimeout) {
|
|
1831
|
+
clearTimeout(this._reconnectionTimeout);
|
|
1832
|
+
this._reconnectionTimeout = void 0;
|
|
1833
|
+
}
|
|
1834
|
+
this._abortController?.abort();
|
|
1835
|
+
this.onclose?.();
|
|
1836
|
+
}
|
|
1837
|
+
async send(message, options) {
|
|
1838
|
+
try {
|
|
1839
|
+
const { resumptionToken, onresumptiontoken } = options || {};
|
|
1840
|
+
if (resumptionToken) {
|
|
1841
|
+
this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
|
|
1842
|
+
return;
|
|
1843
|
+
}
|
|
1844
|
+
const headers = await this._commonHeaders();
|
|
1845
|
+
headers.set("content-type", "application/json");
|
|
1846
|
+
headers.set("accept", "application/json, text/event-stream");
|
|
1847
|
+
const init = {
|
|
1848
|
+
...this._requestInit,
|
|
1849
|
+
method: "POST",
|
|
1850
|
+
headers,
|
|
1851
|
+
body: JSON.stringify(message),
|
|
1852
|
+
signal: this._abortController?.signal
|
|
1853
|
+
};
|
|
1854
|
+
const response = await (this._fetch ?? fetch)(this._url, init);
|
|
1855
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
1856
|
+
if (sessionId) {
|
|
1857
|
+
this._sessionId = sessionId;
|
|
1858
|
+
}
|
|
1859
|
+
if (!response.ok) {
|
|
1860
|
+
const text = await response.text().catch(() => null);
|
|
1861
|
+
if (response.status === 401 && this._authProvider) {
|
|
1862
|
+
if (this._hasCompletedAuthFlow) {
|
|
1863
|
+
throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
|
|
1864
|
+
}
|
|
1865
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
1866
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
1867
|
+
this._scope = scope;
|
|
1868
|
+
const result = await auth(this._authProvider, {
|
|
1869
|
+
serverUrl: this._url,
|
|
1870
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1871
|
+
scope: this._scope,
|
|
1872
|
+
fetchFn: this._fetchWithInit
|
|
1873
|
+
});
|
|
1874
|
+
if (result !== "AUTHORIZED") {
|
|
1875
|
+
throw new UnauthorizedError();
|
|
1876
|
+
}
|
|
1877
|
+
this._hasCompletedAuthFlow = true;
|
|
1878
|
+
return this.send(message);
|
|
1879
|
+
}
|
|
1880
|
+
if (response.status === 403 && this._authProvider) {
|
|
1881
|
+
const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
|
|
1882
|
+
if (error === "insufficient_scope") {
|
|
1883
|
+
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
1884
|
+
if (this._lastUpscopingHeader === wwwAuthHeader) {
|
|
1885
|
+
throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
|
|
1886
|
+
}
|
|
1887
|
+
if (scope) {
|
|
1888
|
+
this._scope = scope;
|
|
1889
|
+
}
|
|
1890
|
+
if (resourceMetadataUrl) {
|
|
1891
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
1892
|
+
}
|
|
1893
|
+
this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
|
|
1894
|
+
const result = await auth(this._authProvider, {
|
|
1895
|
+
serverUrl: this._url,
|
|
1896
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
1897
|
+
scope: this._scope,
|
|
1898
|
+
fetchFn: this._fetch
|
|
1899
|
+
});
|
|
1900
|
+
if (result !== "AUTHORIZED") {
|
|
1901
|
+
throw new UnauthorizedError();
|
|
1902
|
+
}
|
|
1903
|
+
return this.send(message);
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
|
|
1907
|
+
}
|
|
1908
|
+
this._hasCompletedAuthFlow = false;
|
|
1909
|
+
this._lastUpscopingHeader = void 0;
|
|
1910
|
+
if (response.status === 202) {
|
|
1911
|
+
await response.body?.cancel();
|
|
1912
|
+
if (isInitializedNotification(message)) {
|
|
1913
|
+
this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
|
|
1914
|
+
}
|
|
1915
|
+
return;
|
|
1916
|
+
}
|
|
1917
|
+
const messages = Array.isArray(message) ? message : [message];
|
|
1918
|
+
const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
|
|
1919
|
+
const contentType = response.headers.get("content-type");
|
|
1920
|
+
if (hasRequests) {
|
|
1921
|
+
if (contentType?.includes("text/event-stream")) {
|
|
1922
|
+
this._handleSseStream(response.body, { onresumptiontoken }, false);
|
|
1923
|
+
} else if (contentType?.includes("application/json")) {
|
|
1924
|
+
const data = await response.json();
|
|
1925
|
+
const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
|
|
1926
|
+
for (const msg of responseMessages) {
|
|
1927
|
+
this.onmessage?.(msg);
|
|
1928
|
+
}
|
|
1929
|
+
} else {
|
|
1930
|
+
await response.body?.cancel();
|
|
1931
|
+
throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
|
|
1932
|
+
}
|
|
1933
|
+
} else {
|
|
1934
|
+
await response.body?.cancel();
|
|
1935
|
+
}
|
|
1936
|
+
} catch (error) {
|
|
1937
|
+
this.onerror?.(error);
|
|
1938
|
+
throw error;
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
get sessionId() {
|
|
1942
|
+
return this._sessionId;
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Terminates the current session by sending a DELETE request to the server.
|
|
1946
|
+
*
|
|
1947
|
+
* Clients that no longer need a particular session
|
|
1948
|
+
* (e.g., because the user is leaving the client application) SHOULD send an
|
|
1949
|
+
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
|
|
1950
|
+
* terminate the session.
|
|
1951
|
+
*
|
|
1952
|
+
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
|
|
1953
|
+
* the server does not allow clients to terminate sessions.
|
|
1954
|
+
*/
|
|
1955
|
+
async terminateSession() {
|
|
1956
|
+
if (!this._sessionId) {
|
|
1957
|
+
return;
|
|
1958
|
+
}
|
|
1959
|
+
try {
|
|
1960
|
+
const headers = await this._commonHeaders();
|
|
1961
|
+
const init = {
|
|
1962
|
+
...this._requestInit,
|
|
1963
|
+
method: "DELETE",
|
|
1964
|
+
headers,
|
|
1965
|
+
signal: this._abortController?.signal
|
|
1966
|
+
};
|
|
1967
|
+
const response = await (this._fetch ?? fetch)(this._url, init);
|
|
1968
|
+
await response.body?.cancel();
|
|
1969
|
+
if (!response.ok && response.status !== 405) {
|
|
1970
|
+
throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
|
|
1971
|
+
}
|
|
1972
|
+
this._sessionId = void 0;
|
|
1973
|
+
} catch (error) {
|
|
1974
|
+
this.onerror?.(error);
|
|
1975
|
+
throw error;
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
setProtocolVersion(version) {
|
|
1979
|
+
this._protocolVersion = version;
|
|
1980
|
+
}
|
|
1981
|
+
get protocolVersion() {
|
|
1982
|
+
return this._protocolVersion;
|
|
1983
|
+
}
|
|
1984
|
+
/**
|
|
1985
|
+
* Resume an SSE stream from a previous event ID.
|
|
1986
|
+
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
|
|
1987
|
+
*
|
|
1988
|
+
* @param lastEventId The event ID to resume from
|
|
1989
|
+
* @param options Optional callback to receive new resumption tokens
|
|
1990
|
+
*/
|
|
1991
|
+
async resumeStream(lastEventId, options) {
|
|
1992
|
+
await this._startOrAuthSse({
|
|
1993
|
+
resumptionToken: lastEventId,
|
|
1994
|
+
onresumptiontoken: options?.onresumptiontoken
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1997
|
+
};
|
|
1998
|
+
|
|
1999
|
+
export {
|
|
2000
|
+
UnauthorizedError,
|
|
2001
|
+
SseError,
|
|
2002
|
+
SSEClientTransport,
|
|
2003
|
+
StreamableHTTPError,
|
|
2004
|
+
StreamableHTTPClientTransport
|
|
2005
|
+
};
|