@vite-hub/source 0.0.3 → 0.1.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.
Files changed (44) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +302 -31
  3. package/dist/auth-B-tX_rp0.js +1426 -0
  4. package/dist/client-BwstxtdY.js +8280 -0
  5. package/dist/client.d.ts +49 -0
  6. package/dist/client.js +179 -0
  7. package/dist/collection-B_4w_J8h.d.ts +257 -0
  8. package/dist/collection-cursor-WzV1Jd6v.js +124 -0
  9. package/dist/collection-route-BplWPxHR.js +10 -0
  10. package/dist/drizzle.d.ts +41 -0
  11. package/dist/drizzle.js +89 -0
  12. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  13. package/dist/file-BX0FSvgE.js +60 -0
  14. package/dist/file-DadN9dbN.d.ts +19 -0
  15. package/dist/file.d.ts +2 -0
  16. package/dist/file.js +2 -0
  17. package/dist/files.d.ts +15 -0
  18. package/dist/files.js +38 -0
  19. package/dist/github.d.ts +20 -0
  20. package/dist/github.js +1332 -0
  21. package/dist/glob-BmFqTvJY.js +993 -0
  22. package/dist/glob.d.ts +23 -0
  23. package/dist/glob.js +2 -0
  24. package/dist/index.d.ts +165 -172
  25. package/dist/index.js +600 -1113
  26. package/dist/markdown.d.ts +5 -0
  27. package/dist/markdown.js +10 -0
  28. package/dist/mcp.d.ts +151 -0
  29. package/dist/mcp.js +497 -0
  30. package/dist/mrmime-40h5OOIp.js +448 -0
  31. package/dist/path-BS8rYm0n.js +1956 -0
  32. package/dist/path-DOBpV8ol.js +32 -0
  33. package/dist/server.d.ts +265 -0
  34. package/dist/server.js +149 -0
  35. package/dist/sse-D9gqqNPj.js +448 -0
  36. package/dist/streamableHttp-BL-E7pl5.js +509 -0
  37. package/dist/types-BigOktIj.d.ts +93 -0
  38. package/dist/types-CoWcW8oz.js +7590 -0
  39. package/dist/vite.d.ts +162 -0
  40. package/dist/vite.js +2284 -0
  41. package/package.json +102 -17
  42. package/tsconfig.vite.json +6 -0
  43. package/types/source/fallback.d.ts +1 -0
  44. package/types/source/index.d.ts +1 -0
@@ -0,0 +1,5 @@
1
+ import { t as FileSource } from "./types-BigOktIj.js";
2
+ import { n as FileSourceOptions } from "./file-DadN9dbN.js";
3
+ //#region src/sources/markdown.d.ts
4
+ export declare function markdown<const TKey extends string = string>(options: FileSourceOptions<TKey>): FileSource<TKey>;
5
+ //#endregion
@@ -0,0 +1,10 @@
1
+ import { t as file } from "./file-BX0FSvgE.js";
2
+ //#region src/sources/markdown.ts
3
+ function markdown(options) {
4
+ return file({
5
+ ...options,
6
+ mediaType: Object.hasOwn(options, "mediaType") && options.mediaType ? options.mediaType : "text/markdown"
7
+ });
8
+ }
9
+ //#endregion
10
+ export { markdown };
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,151 @@
1
+ import { c as SourceContext, o as SourceCacheOptions, t as FileSource } from "./types-BigOktIj.js";
2
+ //#region src/sources/mcp-resources.d.ts
3
+ interface McpResourcesRequestOptions {
4
+ maxTotalTimeout?: number;
5
+ onprogress?: (progress: {
6
+ message?: string;
7
+ progress: number;
8
+ total?: number;
9
+ }) => void;
10
+ onresumptiontoken?: (token: string) => void;
11
+ relatedRequestId?: number | string;
12
+ relatedTask?: {
13
+ taskId: string;
14
+ };
15
+ resetTimeoutOnProgress?: boolean;
16
+ resumptionToken?: string;
17
+ signal?: AbortSignal;
18
+ task?: {
19
+ pollInterval?: number;
20
+ ttl?: number;
21
+ };
22
+ timeout?: number;
23
+ }
24
+ interface McpResourceDescriptor {
25
+ _meta?: Record<string, unknown>;
26
+ annotations?: {
27
+ audience?: Array<"assistant" | "user">;
28
+ lastModified?: string;
29
+ priority?: number;
30
+ };
31
+ description?: string;
32
+ icons?: Array<{
33
+ mimeType?: string;
34
+ sizes?: string[];
35
+ src: string;
36
+ theme?: "dark" | "light";
37
+ }>;
38
+ mimeType?: string;
39
+ name: string;
40
+ size?: number;
41
+ title?: string;
42
+ uri: string;
43
+ }
44
+ type McpResourceContent = {
45
+ _meta?: Record<string, unknown>;
46
+ blob: string;
47
+ mimeType?: string;
48
+ uri: string;
49
+ } | {
50
+ _meta?: Record<string, unknown>;
51
+ mimeType?: string;
52
+ text: string;
53
+ uri: string;
54
+ };
55
+ type McpResourcesMessage = {
56
+ id: number | string;
57
+ jsonrpc: "2.0";
58
+ method: string;
59
+ params?: {
60
+ [key: string]: unknown;
61
+ _meta?: Record<string, unknown>;
62
+ };
63
+ } | {
64
+ id?: never;
65
+ jsonrpc: "2.0";
66
+ method: string;
67
+ params?: {
68
+ [key: string]: unknown;
69
+ _meta?: Record<string, unknown>;
70
+ };
71
+ } | {
72
+ id: number | string;
73
+ jsonrpc: "2.0";
74
+ method?: never;
75
+ result: {
76
+ [key: string]: unknown;
77
+ _meta?: Record<string, unknown>;
78
+ };
79
+ } | {
80
+ error: {
81
+ code: number;
82
+ data?: unknown;
83
+ message: string;
84
+ };
85
+ id: number | string;
86
+ jsonrpc: "2.0";
87
+ method?: never;
88
+ };
89
+ interface McpResourcesTransport {
90
+ close(): Promise<void>;
91
+ onclose?: () => void;
92
+ onerror?: (error: Error) => void;
93
+ onmessage?: (message: McpResourcesMessage) => void;
94
+ send(message: McpResourcesMessage): Promise<void>;
95
+ start(): Promise<void>;
96
+ }
97
+ interface McpResourcesClient {
98
+ close?: () => void | Promise<void>;
99
+ getServerVersion?: () => {
100
+ name: string;
101
+ version: string;
102
+ } | undefined;
103
+ listResources: (params?: {
104
+ cursor?: string;
105
+ }, options?: McpResourcesRequestOptions) => Promise<{
106
+ nextCursor?: string;
107
+ resources: McpResourceDescriptor[];
108
+ }>;
109
+ readResource: (params: {
110
+ uri: string;
111
+ }, options?: McpResourcesRequestOptions) => Promise<{
112
+ contents: McpResourceContent[];
113
+ }>;
114
+ serverInfo?: unknown;
115
+ }
116
+ type McpResourcesTransportConfig = McpResourcesTransport | {
117
+ authProvider?: unknown;
118
+ fetch?: (url: string | URL, init?: RequestInit) => Promise<Response>;
119
+ reconnectionOptions?: {
120
+ initialReconnectionDelay: number;
121
+ maxReconnectionDelay: number;
122
+ maxRetries: number;
123
+ reconnectionDelayGrowFactor: number;
124
+ };
125
+ requestInit?: RequestInit;
126
+ sessionId?: string;
127
+ type?: "http";
128
+ url: string | URL;
129
+ } | {
130
+ authProvider?: unknown;
131
+ eventSourceInit?: unknown;
132
+ fetch?: (url: string | URL, init?: RequestInit) => Promise<Response>;
133
+ requestInit?: RequestInit;
134
+ type: "sse";
135
+ url: string | URL;
136
+ };
137
+ interface McpResourcesClientConfig {
138
+ transport: McpResourcesTransportConfig;
139
+ }
140
+ type McpResourcesServer = McpResourcesClient | McpResourcesClientConfig | ((ctx: SourceContext) => McpResourcesClient | McpResourcesClientConfig | Promise<McpResourcesClient | McpResourcesClientConfig>);
141
+ interface McpResourcesSourceOptions<TKey extends string = string> {
142
+ cache?: false | SourceCacheOptions;
143
+ ignore?: string | readonly string[];
144
+ include?: string | string[];
145
+ path?: (resource: McpResourceDescriptor) => TKey | string | undefined;
146
+ request?: McpResourcesRequestOptions;
147
+ server: McpResourcesServer;
148
+ }
149
+ export declare function mcpResources<const TKey extends string = string>(options: McpResourcesSourceOptions<TKey>): FileSource<TKey>;
150
+ //#endregion
151
+ export type { McpResourceContent, McpResourceDescriptor, McpResourcesClient, McpResourcesClientConfig, McpResourcesRequestOptions, McpResourcesServer, McpResourcesSourceOptions, McpResourcesTransport, McpResourcesTransportConfig };
package/dist/mcp.js ADDED
@@ -0,0 +1,497 @@
1
+ import { n as matchesAny, t as createPathMatcher } from "./path-BS8rYm0n.js";
2
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
3
+ import { i as sourceError, n as normalizeSafeSourcePath } from "./path-DOBpV8ol.js";
4
+ import { I as ResourceContentsSchema, n as BlobResourceContentsSchema, t as AnnotationsSchema } from "./types-CoWcW8oz.js";
5
+ import { defineDiagnostics } from "nostics";
6
+ //#region ../internal/src/error-diagnostics.ts
7
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
8
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
9
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
10
+ codes: {
11
+ INTERNAL_R0012: dynamicError,
12
+ INTERNAL_R0013: dynamicError,
13
+ INTERNAL_R0014: {
14
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
15
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
16
+ },
17
+ INTERNAL_R0020: {
18
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
19
+ why: ({ message }) => message === void 0 ? "" : String(message)
20
+ },
21
+ INTERNAL_R0021: {
22
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
23
+ why: ({ message }) => message === void 0 ? "" : String(message)
24
+ },
25
+ INTERNAL_R0022: {
26
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
27
+ why: ({ message }) => message === void 0 ? "" : String(message)
28
+ },
29
+ INTERNAL_R0024: {
30
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
31
+ why: ({ message }) => message === void 0 ? "" : String(message)
32
+ },
33
+ INTERNAL_R0023: {
34
+ fix: "Ask for access to the section of this operation.",
35
+ why: ({ message }) => message === void 0 ? "" : String(message)
36
+ },
37
+ INTERNAL_B0001: dynamicError,
38
+ INTERNAL_B0002: dynamicError,
39
+ INTERNAL_B0003: dynamicError,
40
+ INTERNAL_B0004: dynamicError,
41
+ INTERNAL_B0005: dynamicError,
42
+ INTERNAL_B0006: dynamicError,
43
+ INTERNAL_B0007: dynamicError,
44
+ INTERNAL_B0008: dynamicError,
45
+ INTERNAL_B0009: dynamicError,
46
+ INTERNAL_B0010: dynamicError,
47
+ INTERNAL_B0011: dynamicError,
48
+ INTERNAL_B0012: dynamicError,
49
+ INTERNAL_B0013: dynamicError,
50
+ INTERNAL_B0014: dynamicError,
51
+ INTERNAL_B0015: dynamicError,
52
+ INTERNAL_B0016: dynamicError,
53
+ INTERNAL_B0017: dynamicError,
54
+ INTERNAL_B0018: dynamicError,
55
+ INTERNAL_B0019: dynamicError,
56
+ INTERNAL_B0020: dynamicError,
57
+ INTERNAL_B0021: dynamicError,
58
+ INTERNAL_B0022: dynamicError,
59
+ INTERNAL_B0023: dynamicError,
60
+ INTERNAL_B0024: dynamicError,
61
+ INTERNAL_B0025: dynamicError,
62
+ INTERNAL_B0026: dynamicError,
63
+ INTERNAL_B0027: dynamicError,
64
+ INTERNAL_B0028: dynamicError,
65
+ INTERNAL_B0029: dynamicError,
66
+ INTERNAL_B0030: dynamicError,
67
+ INTERNAL_B0031: dynamicError,
68
+ INTERNAL_B0032: dynamicError,
69
+ INTERNAL_B0033: dynamicError,
70
+ INTERNAL_B0034: dynamicError,
71
+ INTERNAL_B0035: dynamicError,
72
+ INTERNAL_B0036: dynamicError,
73
+ INTERNAL_B0037: dynamicError,
74
+ INTERNAL_B0038: dynamicError,
75
+ INTERNAL_B0039: dynamicError,
76
+ INTERNAL_B0040: dynamicError,
77
+ INTERNAL_B0041: dynamicError,
78
+ INTERNAL_B0042: dynamicError,
79
+ INTERNAL_B0043: dynamicError,
80
+ INTERNAL_B0044: dynamicError,
81
+ INTERNAL_B0045: dynamicError,
82
+ INTERNAL_B0046: dynamicError,
83
+ INTERNAL_B0047: dynamicError,
84
+ INTERNAL_B0048: {
85
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
86
+ why: ({ message }) => message === void 0 ? "" : String(message)
87
+ },
88
+ INTERNAL_B0049: {
89
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
90
+ why: ({ message }) => message === void 0 ? "" : String(message)
91
+ },
92
+ INTERNAL_B0050: {
93
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
94
+ why: ({ message }) => message === void 0 ? "" : String(message)
95
+ },
96
+ INTERNAL_R0025: {
97
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
98
+ why: ({ message }) => message === void 0 ? "" : String(message)
99
+ },
100
+ INTERNAL_R0026: {
101
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
102
+ fix: "Review the operation, then run it again with --yes to confirm the change."
103
+ },
104
+ INTERNAL_C0001: dynamicError,
105
+ INTERNAL_C0002: dynamicError,
106
+ INTERNAL_R0001: dynamicError,
107
+ INTERNAL_R0002: dynamicError,
108
+ INTERNAL_R0003: dynamicError,
109
+ INTERNAL_R0004: dynamicError,
110
+ INTERNAL_R0005: dynamicError,
111
+ INTERNAL_R0006: dynamicError,
112
+ INTERNAL_R0007: dynamicError,
113
+ INTERNAL_R0008: dynamicError,
114
+ INTERNAL_R0009: dynamicError,
115
+ INTERNAL_R0010: dynamicError,
116
+ INTERNAL_R0011: dynamicError
117
+ }
118
+ });
119
+ //#endregion
120
+ //#region ../internal/src/abort.ts
121
+ /**
122
+ * Runs `task` and rejects as soon as `signal` aborts, without waiting for the task.
123
+ *
124
+ * The rejection is `signal.reason`. When the reason is absent, it is an `AbortError` with `message`.
125
+ * When `signal` is already aborted, `task` does not run. The task should stop its own work
126
+ * through the same signal.
127
+ */
128
+ function abortable(signal, message, task) {
129
+ return new Promise((resolve, reject) => {
130
+ if (signal?.aborted) {
131
+ reject(abortReason(signal, message));
132
+ return;
133
+ }
134
+ const onAbort = () => reject(abortReason(signal, message));
135
+ signal?.addEventListener("abort", onAbort, { once: true });
136
+ const settle = () => signal?.removeEventListener("abort", onAbort);
137
+ new Promise((resolveTask) => resolveTask(task())).then((value) => {
138
+ settle();
139
+ resolve(value);
140
+ }, (error) => {
141
+ settle();
142
+ reject(error);
143
+ });
144
+ });
145
+ }
146
+ function abortReason(signal, message) {
147
+ if (signal?.reason !== void 0) return signal.reason;
148
+ const error = internalErrorDiagnostics.INTERNAL_R0003({ message });
149
+ error.name = "AbortError";
150
+ return error;
151
+ }
152
+ //#endregion
153
+ //#region src/sources/mcp-resources.ts
154
+ const mcpInterruptedMessage = "[vitehub] MCP Resource Source operation was interrupted.";
155
+ function isMcpResourcesClient(value) {
156
+ return typeof value === "object" && value !== null && hasDeclaredFunction(value, "listResources") && hasDeclaredFunction(value, "readResource");
157
+ }
158
+ function isMcpResourcesClientConfig(value) {
159
+ return typeof value === "object" && value !== null && hasDeclaredProperty(value, "transport") && (isMcpTransport(Reflect.get(value, "transport")) || isMcpTransportConfig(Reflect.get(value, "transport")));
160
+ }
161
+ function isMcpTransport(value) {
162
+ return typeof value === "object" && value !== null && hasDeclaredFunction(value, "close") && hasDeclaredFunction(value, "send") && hasDeclaredFunction(value, "start");
163
+ }
164
+ function isMcpTransportConfig(value) {
165
+ return typeof value === "object" && value !== null && Object.hasOwn(value, "url") && (!Reflect.has(value, "type") || Object.hasOwn(value, "type") && (Reflect.get(value, "type") === "http" || Reflect.get(value, "type") === "sse"));
166
+ }
167
+ function hasDeclaredProperty(value, key) {
168
+ if (typeof value !== "object" || value === null) return false;
169
+ if (Object.hasOwn(value, key)) return true;
170
+ let prototype = Object.getPrototypeOf(value);
171
+ while (prototype && prototype !== Object.prototype) {
172
+ if (Object.hasOwn(prototype, key)) {
173
+ const constructor = Object.hasOwn(prototype, "constructor") ? prototype.constructor : void 0;
174
+ return typeof constructor === "function" && constructor.prototype === prototype && /^class\b/.test(Function.prototype.toString.call(constructor));
175
+ }
176
+ prototype = Object.getPrototypeOf(prototype);
177
+ }
178
+ return false;
179
+ }
180
+ function hasDeclaredFunction(value, key) {
181
+ return hasDeclaredProperty(value, key) && typeof Reflect.get(value, key) === "function";
182
+ }
183
+ async function createMcpTransport(config) {
184
+ if (isMcpTransport(config)) return config;
185
+ const { type = "http", url, ...options } = config;
186
+ if (type === "sse") {
187
+ const { SSEClientTransport } = await import("./sse-D9gqqNPj.js");
188
+ return new SSEClientTransport(new URL(url), options);
189
+ }
190
+ const { StreamableHTTPClientTransport } = await import("./streamableHttp-BL-E7pl5.js");
191
+ return new StreamableHTTPClientTransport(new URL(url), options);
192
+ }
193
+ async function createMcpClient(config) {
194
+ const [{ Client }, transport] = await Promise.all([import("./client-BwstxtdY.js"), createMcpTransport(config.transport)]);
195
+ return {
196
+ client: new Client({
197
+ name: "vitehub-source",
198
+ version: "0.0.1"
199
+ }),
200
+ transport
201
+ };
202
+ }
203
+ async function resolveMcpServer(server, ctx) {
204
+ const resolved = typeof server === "function" ? await server(ctx) : server;
205
+ if (isMcpResourcesClient(resolved) || isMcpResourcesClientConfig(resolved)) return resolved;
206
+ throw sourceErrorDiagnostics.SOURCE_R0021({ message: "[vitehub] mcpResources({ server }) must resolve to an MCP client or MCP client config." });
207
+ }
208
+ function withRequestSignal(request, signal) {
209
+ return {
210
+ ...request,
211
+ signal: request?.signal && request.signal !== signal ? AbortSignal.any([request.signal, signal]) : signal
212
+ };
213
+ }
214
+ async function withMcpClient(server, ctx, request, callback) {
215
+ const signal = ctx.abortSignal && request?.signal ? AbortSignal.any([ctx.abortSignal, request.signal]) : ctx.abortSignal ?? request?.signal;
216
+ const requestSignal = signal ?? new AbortController().signal;
217
+ const resolved = await abortable(signal, mcpInterruptedMessage, () => resolveMcpServer(server, {
218
+ ...ctx,
219
+ abortSignal: signal
220
+ }));
221
+ if (isMcpResourcesClient(resolved)) return await abortable(signal, mcpInterruptedMessage, () => callback(resolved, withRequestSignal(request, requestSignal)));
222
+ const { client, transport } = await createMcpClient(resolved);
223
+ let result;
224
+ try {
225
+ await abortable(signal, mcpInterruptedMessage, () => client.connect(transport, { signal: requestSignal }));
226
+ result = await abortable(signal, mcpInterruptedMessage, () => callback(client, withRequestSignal(request, requestSignal)));
227
+ } catch (error) {
228
+ try {
229
+ await client.close?.();
230
+ } catch (closeError) {
231
+ throw new AggregateError([error, closeError], "[vitehub] MCP Resource Source operation failed for multiple reasons.");
232
+ }
233
+ throw error;
234
+ }
235
+ await client.close?.();
236
+ return result;
237
+ }
238
+ function extensionForMimeType(mimeType) {
239
+ if (!mimeType) return;
240
+ if (mimeType === "application/json") return "json";
241
+ if (mimeType === "text/markdown") return "md";
242
+ if (mimeType === "text/plain") return "txt";
243
+ if (mimeType === "text/html") return "html";
244
+ if (mimeType === "application/xml" || mimeType === "text/xml") return "xml";
245
+ if (mimeType === "application/octet-stream") return "bin";
246
+ }
247
+ function normalizePathSegment(input) {
248
+ return input.normalize("NFKD").replace(/\\/g, "/").replace(/[^\w./-]+/g, "-").replace(/\/+/g, "/").replace(/(^|\/)\.+(?=\/|$)/g, "").replace(/^-+|-+$/g, "");
249
+ }
250
+ function defaultResourcePath(resource) {
251
+ let path = "";
252
+ try {
253
+ const url = new URL(resource.uri);
254
+ const protocol = url.protocol.replace(/:$/, "");
255
+ path = [url.hostname || url.host, decodeURIComponent(url.pathname).replace(/^\/+/, "") || resource.name || protocol].filter(Boolean).join("/");
256
+ } catch {
257
+ path = resource.name || resource.uri;
258
+ }
259
+ let normalized = normalizePathSegment(path);
260
+ if (!normalized) normalized = normalizePathSegment(resource.name || resource.uri);
261
+ const extension = extensionForMimeType(resource.mimeType);
262
+ if (extension && !normalized.split("/").at(-1)?.includes(".")) normalized = `${normalized}.${extension}`;
263
+ return normalizeSafeSourcePath(normalized);
264
+ }
265
+ function resourcePathNeedsContentMimeType(resource, options) {
266
+ if (options.path || resource.mimeType) return false;
267
+ return !defaultResourcePath(resource).split("/").at(-1)?.includes(".");
268
+ }
269
+ function resourceWithContentMimeType(resource, contents) {
270
+ if (resource.mimeType) return resource;
271
+ const content = contents.find((item) => item.uri === resource.uri) || contents[0];
272
+ const mimeType = contents.length > 1 ? "application/json" : content?.mimeType;
273
+ return mimeType ? {
274
+ ...resource,
275
+ mimeType
276
+ } : resource;
277
+ }
278
+ function resourceKey(resource, options, resolved = options.path?.(resource) ?? defaultResourcePath(resource)) {
279
+ return normalizeSafeSourcePath(resolved);
280
+ }
281
+ function isIgnoredBeforeContentRead(resource, candidate, options, matchesIgnore) {
282
+ if (!options.ignore) return false;
283
+ if (options.path || resource.mimeType || candidate.split("/").at(-1)?.includes(".")) return matchesIgnore(candidate);
284
+ return (Array.isArray(options.ignore) ? options.ignore : [options.ignore]).some((pattern) => (pattern === "**" || pattern === "**/*") && matchesAny(candidate, pattern));
285
+ }
286
+ function isRecord(value) {
287
+ return typeof value === "object" && value !== null && !Array.isArray(value);
288
+ }
289
+ function isMcpString(value) {
290
+ return typeof value === "string";
291
+ }
292
+ function isDenseArray(value) {
293
+ if (!Array.isArray(value)) return false;
294
+ for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) return false;
295
+ return true;
296
+ }
297
+ function isOwnMcpString(value, key) {
298
+ return Object.hasOwn(value, key) && isMcpString(Reflect.get(value, key));
299
+ }
300
+ function hasOptionalMcpString(value, key) {
301
+ return hasOptionalMcpField(value, key, isMcpString);
302
+ }
303
+ function hasOptionalMcpField(value, key, validate) {
304
+ if (!Reflect.has(value, key)) return true;
305
+ if (!Object.hasOwn(value, key)) return false;
306
+ const field = Reflect.get(value, key);
307
+ return field === void 0 || validate(field);
308
+ }
309
+ function isMcpNumber(value) {
310
+ return typeof value === "number" && Number.isFinite(value);
311
+ }
312
+ function isMcpMetadata(value) {
313
+ return ResourceContentsSchema.shape._meta.safeParse(value).success;
314
+ }
315
+ function isMcpArrayOf(value, validate) {
316
+ return isDenseArray(value) && value.every(validate);
317
+ }
318
+ function isResourceAnnotations(value) {
319
+ return isRecord(value) && hasOptionalMcpField(value, "audience", (audience) => isMcpArrayOf(audience, (role) => role === "assistant" || role === "user")) && hasOptionalMcpString(value, "lastModified") && hasOptionalMcpField(value, "priority", isMcpNumber) && AnnotationsSchema.safeParse(value).success;
320
+ }
321
+ function isResourceIcon(value) {
322
+ return isRecord(value) && isOwnMcpString(value, "src") && hasOptionalMcpString(value, "mimeType") && hasOptionalMcpField(value, "sizes", (sizes) => isMcpArrayOf(sizes, isMcpString)) && hasOptionalMcpField(value, "theme", (theme) => theme === "dark" || theme === "light");
323
+ }
324
+ function isResourceDescriptor(value) {
325
+ return isRecord(value) && isOwnMcpString(value, "name") && isOwnMcpString(value, "uri") && hasOptionalMcpString(value, "mimeType") && hasOptionalMcpString(value, "title") && hasOptionalMcpString(value, "description") && hasOptionalMcpField(value, "size", isMcpNumber) && hasOptionalMcpField(value, "_meta", isMcpMetadata) && hasOptionalMcpField(value, "annotations", isResourceAnnotations) && hasOptionalMcpField(value, "icons", (icons) => isMcpArrayOf(icons, isResourceIcon));
326
+ }
327
+ function isResourceContent(value) {
328
+ if (!isRecord(value) || !isOwnMcpString(value, "uri") || !hasOptionalMcpString(value, "mimeType") || !hasOptionalMcpField(value, "_meta", isMcpMetadata)) return false;
329
+ const hasTextKey = Object.hasOwn(value, "text");
330
+ const hasBlobKey = Object.hasOwn(value, "blob");
331
+ const hasText = hasTextKey && isMcpString(Reflect.get(value, "text"));
332
+ const hasBlob = hasBlobKey && BlobResourceContentsSchema.safeParse(value).success;
333
+ return hasText !== hasBlob && (!hasTextKey || hasText) && (!hasBlobKey || hasBlob);
334
+ }
335
+ function parseResourceListPage(value) {
336
+ if (!isRecord(value)) throw sourceError("[vitehub] mcpResources server returned an invalid listResources response.");
337
+ if (!Object.hasOwn(value, "resources") || Reflect.has(value, "nextCursor") && !Object.hasOwn(value, "nextCursor")) throw sourceError("[vitehub] mcpResources server returned an invalid listResources response.");
338
+ const resources = Reflect.get(value, "resources");
339
+ const nextCursor = Object.hasOwn(value, "nextCursor") ? Reflect.get(value, "nextCursor") : void 0;
340
+ if (!isDenseArray(resources) || resources.some((resource) => !isResourceDescriptor(resource)) || nextCursor !== void 0 && !isMcpString(nextCursor)) throw sourceError("[vitehub] mcpResources server returned an invalid listResources response.");
341
+ return {
342
+ nextCursor,
343
+ resources
344
+ };
345
+ }
346
+ function parseResourceContents(value) {
347
+ if (!isRecord(value)) throw sourceError("[vitehub] mcpResources server returned an invalid readResource response.");
348
+ if (!Object.hasOwn(value, "contents")) throw sourceError("[vitehub] mcpResources server returned an invalid readResource response.");
349
+ const contents = Reflect.get(value, "contents");
350
+ if (!isDenseArray(contents) || contents.some((content) => !isResourceContent(content))) throw sourceError("[vitehub] mcpResources server returned an invalid readResource response.");
351
+ return contents;
352
+ }
353
+ async function listAllResources(client, request) {
354
+ const resources = [];
355
+ const seenCursors = /* @__PURE__ */ new Set();
356
+ let cursor;
357
+ do {
358
+ if (cursor !== void 0) {
359
+ if (seenCursors.has(cursor)) throw sourceError("[vitehub] mcpResources server returned the same pagination cursor twice.");
360
+ seenCursors.add(cursor);
361
+ }
362
+ const page = parseResourceListPage(await client.listResources(cursor === void 0 ? void 0 : { cursor }, request));
363
+ for (const resource of page.resources) resources.push(resource);
364
+ cursor = page.nextCursor;
365
+ } while (cursor !== void 0);
366
+ return resources;
367
+ }
368
+ async function readResourceContents(client, resource, request) {
369
+ return parseResourceContents(await client.readResource({ uri: resource.uri }, request));
370
+ }
371
+ async function createEntries(resources, options, client) {
372
+ const entries = [];
373
+ const seen = /* @__PURE__ */ new Map();
374
+ const matchesInclude = createPathMatcher(options.include);
375
+ const matchesIgnore = options.ignore ? createPathMatcher(options.ignore) : () => false;
376
+ for (const resource of resources) {
377
+ const candidate = resourceKey(resource, options);
378
+ if (isIgnoredBeforeContentRead(resource, candidate, options, matchesIgnore)) continue;
379
+ let contents;
380
+ let resolvedResource = resource;
381
+ if (client && resourcePathNeedsContentMimeType(resource, options)) {
382
+ contents = await readResourceContents(client, resource, options.request);
383
+ resolvedResource = resourceWithContentMimeType(resource, contents);
384
+ }
385
+ const key = resourceKey(resolvedResource, options, options.path ? candidate : void 0);
386
+ if (!matchesInclude(key) || matchesIgnore(key)) continue;
387
+ const existingUri = seen.get(key);
388
+ if (seen.has(key)) throw sourceError(`[vitehub] mcpResources produced duplicate path ${JSON.stringify(key)} for ${JSON.stringify(existingUri)} and ${JSON.stringify(resource.uri)}.`);
389
+ seen.set(key, resource.uri);
390
+ entries.push({
391
+ contents,
392
+ key,
393
+ resource: resolvedResource
394
+ });
395
+ }
396
+ return entries;
397
+ }
398
+ function decodeBase64(value) {
399
+ const normalized = value.replace(/[\t\n\f\r ]/g, "");
400
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(normalized) || normalized.length % 4 === 1 || /=[A-Za-z0-9+/]/.test(normalized)) throw sourceError("[vitehub] MCP resource returned invalid base64 content.");
401
+ if (globalThis.Buffer) return new Uint8Array(globalThis.Buffer.from(normalized, "base64"));
402
+ const binary = atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="));
403
+ const bytes = new Uint8Array(binary.length);
404
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
405
+ return bytes;
406
+ }
407
+ function contentToSourceContent(content) {
408
+ if (Object.hasOwn(content, "text") && "text" in content && typeof content.text === "string") return content.text;
409
+ if (Object.hasOwn(content, "blob") && "blob" in content && typeof content.blob === "string") return decodeBase64(content.blob);
410
+ return "";
411
+ }
412
+ function createResourceItem(key, resource, contents) {
413
+ const content = contents.find((item) => item.uri === resource.uri) || contents[0];
414
+ if (!content) throw sourceError(`[vitehub] mcpResources could not read resource ${JSON.stringify(resource.uri)}.`);
415
+ const multipleContents = contents.length > 1;
416
+ const metadata = {
417
+ name: resource.name,
418
+ serverResourceCount: contents.length,
419
+ uri: resource.uri
420
+ };
421
+ if (resource.description !== void 0) metadata.description = resource.description;
422
+ if (resource.size !== void 0) metadata.size = resource.size;
423
+ if (resource.title !== void 0) metadata.title = resource.title;
424
+ return {
425
+ key,
426
+ path: key,
427
+ content: multipleContents ? JSON.stringify(contents, null, 2) : contentToSourceContent(content),
428
+ mediaType: multipleContents ? "application/json" : content.mimeType || resource.mimeType,
429
+ metadata
430
+ };
431
+ }
432
+ function mcpResources(options) {
433
+ if (!options || typeof options !== "object" || !hasDeclaredProperty(options, "server") || !options.server) throw sourceErrorDiagnostics.SOURCE_R0022({ message: "[vitehub] mcpResources({ server }) requires an MCP server." });
434
+ async function getEntries(ctx) {
435
+ return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
436
+ return await createEntries(await listAllResources(client, request), {
437
+ ...options,
438
+ request
439
+ }, client);
440
+ });
441
+ }
442
+ async function getItems(ctx) {
443
+ return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
444
+ const scopedOptions = {
445
+ ...options,
446
+ request
447
+ };
448
+ const entries = await createEntries(await listAllResources(client, request), scopedOptions, client);
449
+ return await Promise.all(entries.map(async ({ contents, key, resource }) => {
450
+ return createResourceItem(key, resource, contents ?? await readResourceContents(client, resource, request));
451
+ }));
452
+ });
453
+ }
454
+ return {
455
+ cache: options.cache,
456
+ fingerprint: {
457
+ ignore: options.ignore,
458
+ include: options.include,
459
+ server: typeof options.server === "function" ? "[function]" : isMcpResourcesClient(options.server) ? {
460
+ client: true,
461
+ serverInfo: options.server.serverInfo
462
+ } : options.server
463
+ },
464
+ name: "mcpResources",
465
+ async getKeys(ctx) {
466
+ return (await getEntries(ctx)).map((entry) => entry.key);
467
+ },
468
+ async getItems(ctx) {
469
+ return await getItems(ctx);
470
+ },
471
+ async getMeta(key, ctx) {
472
+ const entry = (await getEntries(ctx)).find((entry) => entry.key === key);
473
+ if (!entry) return;
474
+ return {
475
+ description: entry.resource.description,
476
+ mimeType: entry.resource.mimeType,
477
+ name: entry.resource.name,
478
+ size: entry.resource.size,
479
+ title: entry.resource.title,
480
+ uri: entry.resource.uri
481
+ };
482
+ },
483
+ async getItem(key, ctx) {
484
+ return await withMcpClient(options.server, ctx, options.request, async (client, request) => {
485
+ const entry = (await createEntries(await listAllResources(client, request), {
486
+ ...options,
487
+ request
488
+ }, client)).find((entry) => entry.key === key);
489
+ if (!entry) throw sourceError(`[vitehub] mcpResources could not find ${JSON.stringify(key)}.`);
490
+ const result = entry.contents ?? await readResourceContents(client, entry.resource, request);
491
+ return createResourceItem(key, entry.resource, result);
492
+ });
493
+ }
494
+ };
495
+ }
496
+ //#endregion
497
+ export { mcpResources };