local-mcp-manager 0.5.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ // Read-only MCP Registry search for the workbench "add from directory" flow.
2
+ // Public metadata only: a picked entry becomes a prefilled draft that the user
3
+ // still edits and confirms through the ordinary save flow. Nothing here writes
4
+ // configuration or contacts the registry with credentials.
5
+ const ENDPOINT = 'https://registry.modelcontextprotocol.io/v0/servers'
6
+ const LIMITS = {rowsMax: 20, timeoutMs: 15000, queryMax: 100, descMax: 200, attempts: 2, retryDelayMs: 800}
7
+ const PACKAGE_LIMITS = {refMax: 300, versionMax: 255, metadataItemsMax: 64, argsMax: 12, envMax: 8}
8
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
9
+ const PYPI_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/
10
+ const SEMVER = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*))?(?:\+[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)?$/
11
+ // PEP 440 version grammar, without whitespace or requirement operators.
12
+ const PEP440 = /^v?(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*(?:[-_.]?(?:alpha|beta|preview|pre|rc|a|b|c)[-_.]?[0-9]*)?(?:-[0-9]+|[-_.]?(?:post|rev|r)[-_.]?[0-9]*)?(?:[-_.]?dev[-_.]?[0-9]*)?(?:\+[a-z0-9]+(?:[-_.][a-z0-9]+)*)?$/i
13
+ const OCI_REF = /^([^/]+)\/([a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+)(?::([A-Za-z0-9_][A-Za-z0-9_.-]{0,127}))?(?:@(sha256:[a-f0-9]{64}))?$/
14
+ const OCI_HOSTS = new Set(['docker.io', 'ghcr.io', 'quay.io', 'mcr.microsoft.com'])
15
+ const DNS_LABELS = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/
16
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/
17
+ // Draft env entries are also passed to the launcher. Exclude loader and
18
+ // launcher configuration names, not just names rejected by the store.
19
+ const BLOCKED_ENV = /^(?:__proto__|constructor|prototype|PATH|PATHEXT|HOME|USERPROFILE|SHELL|COMSPEC|BASH_ENV|ENV|NODE_OPTIONS|NODE_PATH|PYTHONHOME|PYTHONPATH|(?:LD|DYLD|DSH|DOCKER|NPM_CONFIG|UV)_.*)$/i
20
+ const ARG_NAME = /^--?[A-Za-z][A-Za-z0-9_-]*$/
21
+ const ARG_VALUE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/
22
+ const clip = (value, max) => typeof value === 'string' ? value.slice(0, max) : ''
23
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value)
24
+ const boundedArray = value => value === undefined ? []
25
+ : Array.isArray(value) && value.length <= PACKAGE_LIMITS.metadataItemsMax ? value : null
26
+ const token = (value, max) => typeof value === 'string' && !!value && value.length <= max && !/\s/.test(value)
27
+
28
+ function packageRefFor(pkg) {
29
+ const id = pkg.identifier, ver = pkg.version
30
+ if (!token(id, PACKAGE_LIMITS.refMax) || pkg.fileSha256 !== undefined) return null
31
+ if (pkg.registryType === 'oci') {
32
+ // The official OCI format places both the registry and version in identifier.
33
+ if (pkg.registryBaseUrl !== undefined || ver !== undefined) return null
34
+ const match = OCI_REF.exec(id)
35
+ if (!match) return null
36
+ const [, host, path, tag, digest] = match
37
+ const isHosted = OCI_HOSTS.has(host) || (DNS_LABELS.test(host)
38
+ && (host.endsWith('.pkg.dev') || host.endsWith('.azurecr.io')))
39
+ return isHosted && host.length + 1 + path.length <= 255
40
+ && (digest || (tag && tag.toLowerCase() !== 'latest')) ? id : null
41
+ }
42
+ if (!token(ver, PACKAGE_LIMITS.versionMax)) return null
43
+ const npm = pkg.registryType === 'npm'
44
+ const base = npm ? 'https://registry.npmjs.org' : 'https://pypi.org'
45
+ if (pkg.registryBaseUrl !== undefined && pkg.registryBaseUrl !== base && pkg.registryBaseUrl !== `${base}/`) return null
46
+ if (npm) {
47
+ const match = SEMVER.exec(ver)
48
+ if (id.length > 214 || !NPM_NAME.test(id) || /^(?:node_modules|favicon\.ico)$/.test(id) || !match
49
+ || match[1]?.split('.').some(part => /^0[0-9]+$/.test(part))) return null
50
+ return `${id}@${ver}`
51
+ }
52
+ return PYPI_NAME.test(id) && PEP440.test(ver) ? `${id}==${ver}` : null
53
+ }
54
+
55
+ const requiredVariables = item => record(item?.variables)
56
+ && Object.values(item.variables).some(variable => !!variable?.isRequired)
57
+ const requiredInput = item => !!item?.isRequired || requiredVariables(item)
58
+
59
+ function envNamesFor(items) {
60
+ const names = new Map()
61
+ for (const item of items) {
62
+ // This draft has one plain input per env name, not a template renderer.
63
+ if (requiredVariables(item)) return null
64
+ const name = item?.name
65
+ if (typeof name !== 'string' || !ENV_NAME.test(name) || BLOCKED_ENV.test(name)) {
66
+ if (requiredInput(item)) return null
67
+ continue
68
+ }
69
+ const key = name.toLowerCase()
70
+ const previous = names.get(key)
71
+ if (previous !== undefined && previous !== name) return null
72
+ names.set(key, name)
73
+ if (names.size > PACKAGE_LIMITS.envMax) return null
74
+ }
75
+ return [...names.values()]
76
+ }
77
+
78
+ function packageArgsFor(items) {
79
+ const args = []
80
+ for (const item of items) {
81
+ if (!record(item)) return null
82
+ // Defaults are suggestions, not fixed input. Never materialize placeholders,
83
+ // secrets, or a repeated/user-supplied argument from directory metadata.
84
+ const value = item.value
85
+ if (value === undefined && !requiredInput(item)) continue
86
+ if (item.isRepeated || item.isSecret || item.variables !== undefined || item.format === 'filepath'
87
+ || !token(value, PACKAGE_LIMITS.refMax) || !ARG_VALUE.test(value)) return null
88
+ let arg
89
+ if (item.type === 'positional') arg = value
90
+ else if (item.type === 'named' && token(item.name, PACKAGE_LIMITS.refMax) && ARG_NAME.test(item.name)) arg = `${item.name}=${value}`
91
+ else return null
92
+ if (arg.length > PACKAGE_LIMITS.refMax || args.length >= PACKAGE_LIMITS.argsMax) return null
93
+ args.push(arg)
94
+ }
95
+ return args
96
+ }
97
+
98
+ function packageDraft(pkg) {
99
+ if (pkg?.transport?.type !== 'stdio') return null
100
+ const registryType = pkg.registryType
101
+ const command = registryType === 'npm' ? 'npx' : registryType === 'pypi' ? 'uvx' : registryType === 'oci' ? 'docker' : null
102
+ if (!command || (pkg.runtimeHint !== undefined && pkg.runtimeHint !== command)) return null
103
+ const packageRef = packageRefFor(pkg)
104
+ if (!packageRef || packageRef.length > PACKAGE_LIMITS.refMax) return null
105
+
106
+ const runtime = boundedArray(pkg.runtimeArguments)
107
+ // No directory-supplied launcher flags. If metadata fixes or requires an
108
+ // unsupported launcher option, skip the candidate rather than losing it.
109
+ if (!runtime || runtime.some(item => !record(item) || requiredInput(item) || item.value !== undefined)) return null
110
+ const env = boundedArray(pkg.environmentVariables), params = boundedArray(pkg.packageArguments)
111
+ if (!env || !params) return null
112
+ const envNames = envNamesFor(env), packageArgs = packageArgsFor(params)
113
+ if (!envNames || !packageArgs) return null
114
+
115
+ const prefix = registryType === 'npm' ? ['-y', packageRef]
116
+ : registryType === 'pypi' ? [`${pkg.identifier}@${pkg.version}`]
117
+ : ['run', '--rm', '-i', ...envNames.flatMap(name => ['-e', name]), packageRef]
118
+ return {transport: 'stdio', url: null, command, args: [...prefix, ...packageArgs], headerNames: [], envNames, registryType, packageRef}
119
+ }
120
+
121
+ function reasonOf(error) {
122
+ const name = error?.name, cause = error?.cause?.code ?? error?.code
123
+ if (name === 'TimeoutError' || cause === 'ABORT_ERR' || cause === 'UND_ERR_CONNECT_TIMEOUT') return 'timeout'
124
+ if (cause === 'ENOTFOUND' || cause === 'EAI_AGAIN' || cause === 'UND_ERR_SOCKET') return 'dns'
125
+ if (/TLS|SSL|CERT|certificate|ERR_SSL/.test([name, cause].filter(Boolean).join(' '))) return 'tls'
126
+ return 'network'
127
+ }
128
+
129
+ export function createRegistryClient({fetchImpl = globalThis.fetch, logger} = {}) {
130
+ const unavailable = reason => ({servers: [], source: ENDPOINT, unreachable: true, reason})
131
+ if (typeof fetchImpl !== 'function') return {search: () => unavailable('network')}
132
+ return {
133
+ async search(query) {
134
+ const text = clip(query, LIMITS.queryMax).trim()
135
+ if (!text) return {servers: [], source: ENDPOINT, unreachable: false}
136
+ const url = `${ENDPOINT}?search=${encodeURIComponent(text)}&version=latest&limit=${LIMITS.rowsMax}`
137
+ let payload, lastReason = 'network'
138
+ for (let attempt = 0; attempt < LIMITS.attempts; attempt++) {
139
+ try {
140
+ const response = await fetchImpl(url, {signal: AbortSignal.timeout(LIMITS.timeoutMs),
141
+ headers: {accept: 'application/json'}, redirect: 'error'})
142
+ if (!response.ok) {
143
+ lastReason = `http-${response.status}`
144
+ logger?.warn?.(`MCP registry search returned ${response.status}`)
145
+ return unavailable(lastReason)
146
+ }
147
+ payload = await response.json()
148
+ break
149
+ } catch (error) {
150
+ lastReason = reasonOf(error)
151
+ logger?.warn?.(`MCP registry search failed (${lastReason}, attempt ${attempt + 1}/${LIMITS.attempts})`)
152
+ if (attempt + 1 < LIMITS.attempts) await new Promise(resolve => setTimeout(resolve, LIMITS.retryDelayMs))
153
+ }
154
+ }
155
+ if (!payload) return unavailable(lastReason)
156
+ const rows = Array.isArray(payload?.servers) ? payload.servers : []
157
+ const servers = [], seen = new Set()
158
+ for (const row of rows.slice(0, LIMITS.rowsMax)) {
159
+ const server = row?.server
160
+ if (!server || typeof server.name !== 'string' || !server.name || seen.has(server.name)) continue
161
+ const meta = row?._meta?.['io.modelcontextprotocol.registry/official']
162
+ const base = {name: server.name.slice(0, 160), description: clip(server.description, LIMITS.descMax),
163
+ version: clip(server.version, 40), status: meta?.status === 'active' ? 'active' : meta?.status ? clip(meta.status, 16) : 'unknown',
164
+ websiteUrl: typeof server.websiteUrl === 'string' && /^https:\/\//.test(server.websiteUrl) ? server.websiteUrl.slice(0, 300) : null}
165
+ const remotes = Array.isArray(server.remotes) ? server.remotes : []
166
+ const remote = remotes.find(item => item?.type === 'streamable-http') ?? remotes.find(item => item?.type === 'sse')
167
+ if (remote && typeof remote.url === 'string' && /^https:\/\//.test(remote.url)) {
168
+ seen.add(server.name)
169
+ servers.push({...base, transport: remote.type === 'sse' ? 'sse' : 'streamable-http', url: remote.url.slice(0, 600),
170
+ command: null, args: [], headerNames: (Array.isArray(remote.headers) ? remote.headers : [])
171
+ .map(item => typeof item?.name === 'string' ? item.name.slice(0, 64) : '').filter(Boolean).slice(0, 8), envNames: []})
172
+ continue
173
+ }
174
+ const packages = Array.isArray(server.packages) ? server.packages : []
175
+ for (const candidate of packages.slice(0, PACKAGE_LIMITS.metadataItemsMax)) {
176
+ const pkg = packageDraft(candidate)
177
+ if (!pkg) continue
178
+ seen.add(server.name)
179
+ servers.push({...base, ...pkg})
180
+ break
181
+ }
182
+ }
183
+ return {servers: servers.slice(0, LIMITS.rowsMax), source: ENDPOINT, unreachable: false}
184
+ },
185
+ }
186
+ }
@@ -0,0 +1,294 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { SdkErrorCode, UriTemplate } from '@modelcontextprotocol/client';
3
+
4
+ const MAX_URI = 4096;
5
+ const MAX_VALUE = 1024;
6
+ const MAX_REFERENCES = 32;
7
+ const MAX_NAME = 128;
8
+ const MAX_WATCHES = 16;
9
+ const MAX_PENDING = 64;
10
+ const UPDATED = 'notifications/resources/updated';
11
+ const URI_LITERAL = /^[a-z0-9._~:/?#[\]@!$&'()*+,;=%-]*$/i;
12
+ const SCHEME = /^[a-z][a-z\d+.-]*:/i;
13
+ const BAD_ESCAPE = /%(?![a-f\d]{2})/i;
14
+ const OPERATORS = '+#./;?&';
15
+ const VARNAME = '(?:[a-z0-9_]|%[a-f0-9]{2})+';
16
+ const VARSPEC = new RegExp(`^(${VARNAME}(?:\\.${VARNAME})*)(?:\\*|:([1-9][0-9]{0,3}))?$`, 'i');
17
+ const SDK_SCALAR = new UriTemplate('{value}');
18
+ const SDK_RESERVED_SCALAR = new UriTemplate('{+value}');
19
+
20
+ function validLiteral(value) {
21
+ return URI_LITERAL.test(value) && !BAD_ESCAPE.test(value);
22
+ }
23
+
24
+ function isAbsoluteUri(uri) {
25
+ if (typeof uri !== 'string' || uri.length > MAX_URI || !SCHEME.test(uri)
26
+ || !validLiteral(uri) || uri.indexOf('#') !== uri.lastIndexOf('#')) return false;
27
+ return URL.canParse(uri);
28
+ }
29
+
30
+ function parseTemplate(template) {
31
+ if (typeof template !== 'string' || template.length === 0 || template.length > MAX_URI) {
32
+ throw new Error('Invalid resource template length or type');
33
+ }
34
+ const names = new Set();
35
+ const parts = [];
36
+ let refs = 0;
37
+ let offset = 0;
38
+ for (const match of template.matchAll(/\{([^{}]+)\}/g)) {
39
+ const literal = template.slice(offset, match.index);
40
+ if (!validLiteral(literal)) throw new Error('Invalid resource template literal');
41
+ const expression = match[1];
42
+ const op = OPERATORS.includes(expression[0]) ? expression[0] : '';
43
+ const specs = expression.slice(op.length).split(',');
44
+ refs += specs.length;
45
+ if (refs > MAX_REFERENCES) throw new Error('Too many resource template variables');
46
+ const variables = specs.map(spec => {
47
+ const parsed = VARSPEC.exec(spec);
48
+ if (!parsed || parsed[1].length > MAX_NAME) throw new Error('Invalid resource template variable');
49
+ return { name: parsed[1], prefix: parsed[2] === undefined ? undefined : Number(parsed[2]) };
50
+ });
51
+ // The SDK 2.3.0 parser handles ordinary variable names but treats `;` and
52
+ // `:prefix` as part of the name. Normalize those two before asking it.
53
+ const exprNames = new UriTemplate(`{${op === ';' ? '?' : op}${variables.map(v => v.name).join(',')}}`).variableNames;
54
+ exprNames.forEach(name => names.add(name));
55
+ parts.push({ literal, op, variables });
56
+ offset = match.index + match[0].length;
57
+ }
58
+ const tail = template.slice(offset);
59
+ if (!validLiteral(tail)) throw new Error('Invalid resource template literal');
60
+ if (names.size === 0 && !isAbsoluteUri(template)) throw new Error('Invalid absolute resource URI');
61
+ return { names, parts, tail };
62
+ }
63
+
64
+ /** Returns distinct RFC 6570 names in first-occurrence order. */
65
+ export function resourceTemplateVariables(template) {
66
+ return [...parseTemplate(template).names];
67
+ }
68
+
69
+ function encodeScalar(value, reserved) {
70
+ if (!reserved) {
71
+ return SDK_SCALAR.expand({ value }).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
72
+ }
73
+ // Reserved expansions preserve valid percent triplets and the square bracket
74
+ // delimiters; the SDK uses encodeURI, which encodes both of these.
75
+ return value.split(/(%[a-f0-9]{2}|[\[\]])/i)
76
+ .map((segment, index) => index % 2 ? segment : SDK_RESERVED_SCALAR.expand({ value: segment })).join('');
77
+ }
78
+
79
+ /** Expand only scalar strings. Unknown keys and non-data own properties are
80
+ * rejected; omitted variables follow RFC 6570's undefined-value semantics. */
81
+ export function expandResourceTemplate(template, values = {}) {
82
+ const { names, parts, tail } = parseTemplate(template);
83
+ if (values === null || typeof values !== 'object' || Array.isArray(values)) {
84
+ throw new Error('Invalid resource template values');
85
+ }
86
+ const proto = Object.getPrototypeOf(values);
87
+ if (proto !== null && proto !== Object.prototype) throw new Error('Invalid resource template values');
88
+ const scalars = new Map();
89
+ for (const key of Reflect.ownKeys(values)) {
90
+ if (!names.has(key)) throw new Error('Unknown resource template variable');
91
+ const { value } = Object.getOwnPropertyDescriptor(values, key);
92
+ if (typeof value !== 'string' || value.length > MAX_VALUE || !value.isWellFormed()) {
93
+ throw new Error('Invalid resource template value');
94
+ }
95
+ scalars.set(key, value);
96
+ }
97
+ let result = '';
98
+ for (const { literal, op, variables } of parts) {
99
+ result += literal;
100
+ const named = op === ';' || op === '?' || op === '&';
101
+ const segments = [];
102
+ for (const { name, prefix } of variables) {
103
+ let value = scalars.get(name);
104
+ if (value === undefined) continue;
105
+ if (prefix !== undefined) value = [...value].slice(0, prefix).join('');
106
+ const encoded = encodeScalar(value, op === '+' || op === '#');
107
+ // SDK 2.3.0 omits the operator/escaping on multi-name non-query
108
+ // expressions. Compose scalar expansions with RFC 6570 separators.
109
+ segments.push(!named ? encoded : op === ';' && !encoded ? name : `${name}=${encoded}`);
110
+ }
111
+ if (segments.length) {
112
+ const prefix = op === '+' ? '' : op;
113
+ const separator = op === '?' || op === '&' ? '&' : './;'.includes(op) && op ? op : ',';
114
+ result += prefix + segments.join(separator);
115
+ }
116
+ if (result.length > MAX_URI) throw new Error('Expanded resource URI is too long');
117
+ }
118
+ result += tail;
119
+ if (!isAbsoluteUri(result)) throw new Error('Invalid absolute resource URI');
120
+ return result;
121
+ }
122
+
123
+ const error = (code, message) => Object.assign(new Error(message), { code });
124
+ const cancelled = () => error('cancelled', 'Resource watch generation ended');
125
+ const unsupported = () => error('unsupported', 'Resource subscriptions are not supported');
126
+ const timedOut = () => error('timeout', 'Resource watch operation timed out');
127
+ const failed = () => error('watch-failed', 'Resource watch operation failed');
128
+ const closeHandle = handle => Promise.resolve().then(() => handle?.close?.()).catch(() => {});
129
+
130
+ /** Creates a resource-update handler and subscription state for one connected SDK client generation. */
131
+ export function createResourceWatches(client, generationSignal, { timeoutMs = 60000, isCurrent = () => true } = {}) {
132
+ const timeout = Number.isFinite(timeoutMs) ? Math.max(1, Math.min(300000, Math.trunc(timeoutMs))) : 60000;
133
+ const era = client?.getProtocolEra?.();
134
+ const version = era === undefined ? client?.getNegotiatedProtocolVersion?.() : undefined;
135
+ const modern = era === 'modern' || (typeof version === 'string' && version >= '2026-07-28');
136
+ const watches = new Map();
137
+ let disposed = false;
138
+ let registered = false;
139
+ let running;
140
+ let serial = Promise.resolve();
141
+ let pending = 0;
142
+ const current = () => !generationSignal?.aborted && isCurrent();
143
+ const eligible = client?.getServerCapabilities?.()?.resources?.subscribe === true
144
+ && typeof client.setNotificationHandler === 'function'
145
+ && (modern ? typeof client.listen === 'function' : typeof client.subscribeResource === 'function'
146
+ && typeof client.unsubscribeResource === 'function');
147
+
148
+ function dispose() {
149
+ if (disposed) return;
150
+ disposed = true;
151
+ generationSignal?.removeEventListener('abort', dispose);
152
+ running?.abort(cancelled());
153
+ if (registered) {
154
+ registered = false;
155
+ try { client.removeNotificationHandler?.(UPDATED); } catch { /* Client may already be closed. */ }
156
+ }
157
+ const entries = [...watches.entries()];
158
+ watches.clear();
159
+ if (modern) {
160
+ for (const [, entry] of entries) void closeHandle(entry.handle);
161
+ } else if (entries.length && current()) {
162
+ // On explicit disposal of a still-live generation, make a bounded,
163
+ // best-effort teardown. On generation abort the owner closes the client.
164
+ void serial.then(async () => {
165
+ const deadline = AbortSignal.timeout(timeout);
166
+ const signal = generationSignal ? AbortSignal.any([generationSignal, deadline]) : deadline;
167
+ for (const [uri] of entries) {
168
+ if (signal.aborted || !current()) break;
169
+ try { await client.unsubscribeResource({ uri }, { signal, timeout }); } catch { /* Best effort only. */ }
170
+ }
171
+ }).catch(() => {});
172
+ }
173
+ }
174
+
175
+ function live() {
176
+ if (!disposed && !current()) dispose();
177
+ return !disposed;
178
+ }
179
+
180
+ if (eligible && live()) {
181
+ client.setNotificationHandler(UPDATED, note => {
182
+ if (!live()) return;
183
+ const entry = watches.get(note?.params?.uri);
184
+ if (!entry) return;
185
+ entry.token = randomUUID();
186
+ entry.changedAt = Date.now();
187
+ });
188
+ registered = true;
189
+ generationSignal?.addEventListener('abort', dispose, { once: true });
190
+ live();
191
+ }
192
+
193
+ // Enforce an operation bound even when a transport fails to settle. SDK
194
+ // listen's signal must remain valid after ACK, so cancel only on timeout or
195
+ // pending-generation retirement; established streams are closed by handle.
196
+ async function request(work, onLateResult) {
197
+ const controller = new AbortController();
198
+ const { signal } = controller;
199
+ running = controller;
200
+ const timer = setTimeout(() => controller.abort(timedOut()), timeout);
201
+ let onAbort;
202
+ const abort = new Promise((_, reject) => {
203
+ onAbort = () => reject(signal.reason);
204
+ signal.addEventListener('abort', onAbort, { once: true });
205
+ });
206
+ let cleanup;
207
+ const cleanLate = () => { const job = cleanup; cleanup = undefined; job?.(); };
208
+ const result = Promise.resolve().then(() => {
209
+ signal.throwIfAborted();
210
+ return work({ signal, timeout });
211
+ }).then(value => {
212
+ if (onLateResult) cleanup = () => onLateResult(value);
213
+ if (signal.aborted) cleanLate();
214
+ return value;
215
+ });
216
+ try {
217
+ const value = await Promise.race([result, abort]);
218
+ signal.throwIfAborted();
219
+ return value;
220
+ } catch (cause) {
221
+ if (signal.aborted) {
222
+ cleanLate();
223
+ throw signal.reason;
224
+ }
225
+ if (cause?.code === SdkErrorCode.RequestTimeout) throw timedOut();
226
+ throw failed();
227
+ } finally {
228
+ clearTimeout(timer);
229
+ signal.removeEventListener('abort', onAbort);
230
+ running = undefined;
231
+ }
232
+ }
233
+
234
+ async function apply(uri, enabled) {
235
+ if (!live()) throw cancelled();
236
+ const existing = watches.get(uri);
237
+ if (enabled === Boolean(existing)) return;
238
+ if (!enabled) {
239
+ if (modern) {
240
+ watches.delete(uri);
241
+ await request(() => existing.handle.close());
242
+ } else {
243
+ await request(options => client.unsubscribeResource({ uri }, options));
244
+ watches.delete(uri);
245
+ }
246
+ if (!live()) throw cancelled();
247
+ return;
248
+ }
249
+ if (watches.size >= MAX_WATCHES) throw error('watch-limit', 'Too many resource watches');
250
+ let handle;
251
+ if (modern) {
252
+ handle = await request(options => client.listen({ resourceSubscriptions: [uri] }, options), closeHandle);
253
+ if (!live()) {
254
+ void closeHandle(handle);
255
+ throw cancelled();
256
+ }
257
+ const honored = handle?.honoredFilter?.resourceSubscriptions;
258
+ if (!Array.isArray(honored) || honored.length !== 1 || honored[0] !== uri
259
+ || typeof handle?.close !== 'function' || typeof handle?.closed?.then !== 'function') {
260
+ void closeHandle(handle);
261
+ throw error('unsupported', 'Resource subscription was not acknowledged');
262
+ }
263
+ } else {
264
+ await request(options => client.subscribeResource({ uri }, options));
265
+ if (!live()) throw cancelled();
266
+ }
267
+ const entry = { handle, token: randomUUID(), changedAt: null };
268
+ watches.set(uri, entry);
269
+ if (handle) {
270
+ const ended = () => { if (watches.get(uri) === entry) watches.delete(uri); };
271
+ void Promise.resolve(handle.closed).then(ended, ended);
272
+ }
273
+ }
274
+
275
+ return {
276
+ get supported() { return live() && registered; },
277
+ async set(uri, enabled) {
278
+ if (!live()) throw cancelled();
279
+ if (!registered) throw unsupported();
280
+ if (!isAbsoluteUri(uri)) throw error('invalid-uri', 'Invalid absolute resource URI');
281
+ if (typeof enabled !== 'boolean') throw error('invalid-enabled', 'Invalid resource watch state');
282
+ if (pending >= MAX_PENDING) throw error('watch-limit', 'Too many pending resource watch operations');
283
+ pending++;
284
+ const operation = serial.then(() => apply(uri, enabled));
285
+ serial = operation.catch(() => {});
286
+ try { await operation; } finally { pending--; }
287
+ },
288
+ list() {
289
+ if (!live()) return [];
290
+ return [...watches].map(([uri, { token, changedAt }]) => ({ uri, token, changedAt }));
291
+ },
292
+ dispose,
293
+ };
294
+ }