@vite-hub/source 0.0.1 → 0.0.2

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.
@@ -1,4 +1,4 @@
1
- import { r as Source } from "./types-DgWwkKHY.js";
1
+ import { r as Source } from "./types-f6Lyjq8g.js";
2
2
 
3
3
  //#region src/sources/custom.d.ts
4
4
  declare function custom<const TSource extends Source>(source: TSource): TSource;
@@ -1,4 +1,4 @@
1
- import { a as SourceContent, r as Source } from "./types-DgWwkKHY.js";
1
+ import { a as SourceContent, r as Source } from "./types-f6Lyjq8g.js";
2
2
 
3
3
  //#region src/sources/file.d.ts
4
4
  interface FileSourcePathOptions<TKey extends string = string> {
@@ -0,0 +1,565 @@
1
+ import { a as isSourceError, i as normalizeSourcePath, n as matchesAny, o as sourceError } from "./path-B5QNI5sY.js";
2
+ import { Buffer } from "node:buffer";
3
+ import { defineCachedFunction } from "ocache";
4
+ import { gunzipSync } from "node:zlib";
5
+ import { devNull } from "node:os";
6
+ //#region src/sources/github/archive.ts
7
+ function parseGitHubArchive(bytes) {
8
+ const tar = gunzipSync(bytes);
9
+ const files = [];
10
+ let offset = 0;
11
+ let paxPath;
12
+ while (offset + 512 <= tar.length) {
13
+ const header = tar.subarray(offset, offset + 512);
14
+ if (header.every((byte) => byte === 0)) break;
15
+ const name = readTarString(header, 0, 100);
16
+ const prefix = readTarString(header, 345, 155);
17
+ const path = paxPath || [prefix, name].filter(Boolean).join("/");
18
+ const size = Number.parseInt(readTarString(header, 124, 12).trim() || "0", 8) || 0;
19
+ const type = String.fromCharCode(header[156] || 0);
20
+ const contentStart = offset + 512;
21
+ const contentEnd = contentStart + size;
22
+ const content = tar.subarray(contentStart, contentEnd);
23
+ if (type === "x") paxPath = readPaxPath(content);
24
+ else {
25
+ if (type === "0" || type === "\0") {
26
+ const entryPath = stripArchiveRoot(path);
27
+ if (entryPath) files.push({
28
+ content: new Uint8Array(content),
29
+ path: entryPath
30
+ });
31
+ }
32
+ paxPath = void 0;
33
+ }
34
+ offset = contentStart + Math.ceil(size / 512) * 512;
35
+ }
36
+ return files;
37
+ }
38
+ function readTarString(buffer, offset, length) {
39
+ const slice = buffer.subarray(offset, offset + length);
40
+ const end = slice.indexOf(0);
41
+ return Buffer.from(end === -1 ? slice : slice.subarray(0, end)).toString("utf8");
42
+ }
43
+ function readPaxPath(content) {
44
+ let index = 0;
45
+ while (index < content.length) {
46
+ let space = index;
47
+ while (space < content.length && content[space] !== 32) space++;
48
+ if (space >= content.length) return;
49
+ const length = Number.parseInt(Buffer.from(content.subarray(index, space)).toString("ascii"), 10);
50
+ if (!Number.isFinite(length) || length <= 0 || index + length > content.length) return;
51
+ const record = content.subarray(space + 1, index + length - 1);
52
+ const equals = record.indexOf(61);
53
+ if (equals !== -1 && Buffer.from(record.subarray(0, equals)).toString("utf8") === "path") return Buffer.from(record.subarray(equals + 1)).toString("utf8");
54
+ index += length;
55
+ }
56
+ }
57
+ function stripArchiveRoot(path) {
58
+ const slash = path.indexOf("/");
59
+ if (slash === -1) return;
60
+ return normalizeSourcePath(path.slice(slash + 1));
61
+ }
62
+ //#endregion
63
+ //#region src/sources/github/cache.ts
64
+ function normalizeGitHubCache(options) {
65
+ if (options.cache === false) return;
66
+ if (options.cache && typeof options.cache === "object") return { maxAge: options.cache.maxAge };
67
+ }
68
+ function createGitHubCacheKey(input) {
69
+ return [
70
+ input.kind,
71
+ input.repo,
72
+ input.ref,
73
+ input.root,
74
+ normalizePatternCacheKey(input.include),
75
+ normalizePatternCacheKey(input.exclude),
76
+ input.token,
77
+ input.key || ""
78
+ ].join(":");
79
+ }
80
+ function normalizePatternCacheKey(value) {
81
+ if (!value) return "";
82
+ return Array.isArray(value) ? value.join(",") : value;
83
+ }
84
+ //#endregion
85
+ //#region src/sources/github/client.ts
86
+ async function requestGitHubJson(input) {
87
+ const response = await fetch(input.url, {
88
+ headers: {
89
+ accept: "application/vnd.github+json",
90
+ ...input.token ? { authorization: `Bearer ${input.token}` } : {},
91
+ "user-agent": "vitehub-source",
92
+ "x-github-api-version": "2022-11-28"
93
+ },
94
+ signal: input.signal
95
+ });
96
+ if (!response.ok) {
97
+ if (response.status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) could not access the repository or ref ${JSON.stringify(input.ref)}. Check that the repo exists, the ref exists, and auth can access it.`);
98
+ throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) request failed with ${response.status} for ${input.url}.`);
99
+ }
100
+ return await response.json();
101
+ }
102
+ async function fetchGitHubArchive(input) {
103
+ const response = await fetch(`https://codeload.github.com/${input.repo}/tar.gz/${encodeURIComponent(input.ref)}`, {
104
+ headers: {
105
+ ...input.token ? { authorization: `Bearer ${input.token}` } : {},
106
+ "user-agent": "vitehub-source"
107
+ },
108
+ signal: input.signal
109
+ });
110
+ if (!response.ok) {
111
+ if (response.status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) could not access the repository or ref ${JSON.stringify(input.ref)}. Check that the repo exists and the ref exists.`);
112
+ throw sourceError(`[vitehub] github(${JSON.stringify(input.repo)}) archive request failed with ${response.status}.`);
113
+ }
114
+ return new Uint8Array(await response.arrayBuffer());
115
+ }
116
+ //#endregion
117
+ //#region src/sources/github/git.ts
118
+ function createGitEnv(home, token, baseEnv = process.env) {
119
+ const env = { ...baseEnv };
120
+ for (const key of [
121
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
122
+ "GIT_COMMON_DIR",
123
+ "GIT_CONFIG",
124
+ "GIT_CONFIG_COUNT",
125
+ "GIT_CONFIG_PARAMETERS",
126
+ "GIT_DIR",
127
+ "GIT_GRAFT_FILE",
128
+ "GIT_IMPLICIT_WORK_TREE",
129
+ "GIT_INDEX_FILE",
130
+ "GIT_NO_REPLACE_OBJECTS",
131
+ "GIT_OBJECT_DIRECTORY",
132
+ "GIT_PREFIX",
133
+ "GIT_REPLACE_REF_BASE",
134
+ "GIT_SHALLOW_FILE",
135
+ "GIT_WORK_TREE"
136
+ ]) delete env[key];
137
+ for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(key)) delete env[key];
138
+ Object.assign(env, {
139
+ GCM_INTERACTIVE: "Never",
140
+ GIT_ASKPASS: "",
141
+ GIT_CONFIG_COUNT: token ? "1" : "0",
142
+ GIT_CONFIG_GLOBAL: devNull,
143
+ GIT_CONFIG_NOSYSTEM: "1",
144
+ GIT_TERMINAL_PROMPT: "0",
145
+ HOME: home,
146
+ SSH_ASKPASS: "",
147
+ USERPROFILE: home,
148
+ XDG_CONFIG_HOME: home
149
+ });
150
+ if (!token) return env;
151
+ const credential = Buffer.from(`x-access-token:${token}`).toString("base64");
152
+ env.GIT_CONFIG_KEY_0 = "http.https://github.com/.extraheader";
153
+ env.GIT_CONFIG_VALUE_0 = `AUTHORIZATION: basic ${credential}`;
154
+ return env;
155
+ }
156
+ async function runGit(args, options = {}) {
157
+ const { spawn } = await import("node:child_process");
158
+ return await new Promise((resolve, reject) => {
159
+ const child = spawn("git", args, {
160
+ env: options.env,
161
+ signal: options.signal,
162
+ stdio: [
163
+ "pipe",
164
+ "pipe",
165
+ "pipe"
166
+ ]
167
+ });
168
+ const stdout = [];
169
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
170
+ child.stderr.resume();
171
+ child.stdin.on("error", () => {});
172
+ child.stdin.end();
173
+ child.on("error", reject);
174
+ child.on("close", (code) => {
175
+ if (code === 0) {
176
+ resolve(Buffer.concat(stdout));
177
+ return;
178
+ }
179
+ const command = args[0] === "-C" ? args[2] : args[0];
180
+ reject(/* @__PURE__ */ new Error(`git ${command || "command"} exited with ${code ?? "an unknown status"}.`));
181
+ });
182
+ });
183
+ }
184
+ function isGitSparsePattern(pattern) {
185
+ if (pattern.includes("\0") || pattern.includes("\r") || pattern.includes("\n")) return false;
186
+ if (pattern.split("/").some((segment) => segment === "." || segment === "..")) return false;
187
+ if (!pattern.includes("*")) return !/[?[\]{}()!+@]/.test(pattern);
188
+ if (!pattern.endsWith("/**")) return false;
189
+ return !/[*?[\]{}()!+@]/.test(pattern.slice(0, -3));
190
+ }
191
+ function getGitSparsePatterns(root, include) {
192
+ const patterns = (include ? Array.isArray(include) ? include : [include] : []).map((pattern) => [root, normalizeSourcePath(pattern)].filter(Boolean).join("/")).filter(Boolean);
193
+ if (patterns.some((pattern) => !isGitSparsePattern(pattern))) return;
194
+ if (patterns.length) return [...new Set(patterns)];
195
+ return root && isGitSparsePattern(root) ? [`${root}/**`] : void 0;
196
+ }
197
+ function isGitLfsPointer(content) {
198
+ if (content.byteLength > 64 * 1024) return false;
199
+ const lines = Buffer.from(content).toString("utf8").split(/\r?\n/);
200
+ return lines[0] === "version https://git-lfs.github.com/spec/v1" && lines.some((line) => /^oid sha256:[0-9a-f]{64}$/.test(line)) && lines.some((line) => /^size \d+$/.test(line));
201
+ }
202
+ async function readGitArchiveFiles(dir, input, executeGit, options) {
203
+ input.signal?.throwIfAborted();
204
+ const archive = await executeGit([
205
+ "-C",
206
+ dir,
207
+ "archive",
208
+ "--format=tar.gz",
209
+ "--prefix=archive/",
210
+ input.sha,
211
+ "--",
212
+ ...input.sparsePatterns.map((pattern) => {
213
+ return `:(literal)${pattern.endsWith("/**") ? pattern.slice(0, -3) : pattern}`;
214
+ })
215
+ ], options);
216
+ return parseGitHubArchive(Buffer.from(archive)).map((entry) => {
217
+ const key = input.keyForRepoPath(entry.path);
218
+ if (!key || !input.shouldInclude(key)) return;
219
+ if (isGitLfsPointer(entry.content)) throw new Error("git archive contained a Git LFS pointer; use the GitHub archive instead.");
220
+ return {
221
+ content: entry.content,
222
+ key,
223
+ path: key,
224
+ ref: input.ref,
225
+ sha: input.sha
226
+ };
227
+ }).filter((file) => Boolean(file));
228
+ }
229
+ async function loadGitArchiveFiles(input, executeGit = runGit) {
230
+ const [{ mkdtemp, rm }, { tmpdir }, { join }] = await Promise.all([
231
+ import("node:fs/promises"),
232
+ import("node:os"),
233
+ import("node:path")
234
+ ]);
235
+ const dir = await mkdtemp(join(tmpdir(), "vitehub-github-"));
236
+ try {
237
+ const options = {
238
+ env: createGitEnv(dir, input.token, input.env),
239
+ signal: input.signal
240
+ };
241
+ await executeGit([
242
+ "init",
243
+ "--quiet",
244
+ dir
245
+ ], options);
246
+ await executeGit([
247
+ "-C",
248
+ dir,
249
+ "remote",
250
+ "add",
251
+ "origin",
252
+ input.repositoryUrl || `https://github.com/${input.repo}.git`
253
+ ], options);
254
+ await executeGit([
255
+ "-C",
256
+ dir,
257
+ "config",
258
+ "remote.origin.promisor",
259
+ "true"
260
+ ], options);
261
+ await executeGit([
262
+ "-C",
263
+ dir,
264
+ "config",
265
+ "remote.origin.partialclonefilter",
266
+ "blob:none"
267
+ ], options);
268
+ await executeGit([
269
+ "-C",
270
+ dir,
271
+ "fetch",
272
+ "--depth=1",
273
+ "--filter=blob:none",
274
+ "--no-tags",
275
+ "--",
276
+ "origin",
277
+ `+${input.ref}`
278
+ ], options);
279
+ const sha = Buffer.from(await executeGit([
280
+ "-C",
281
+ dir,
282
+ "rev-parse",
283
+ "FETCH_HEAD"
284
+ ], options)).toString("utf8").trim();
285
+ return await readGitArchiveFiles(dir, {
286
+ ...input,
287
+ sha
288
+ }, executeGit, options);
289
+ } finally {
290
+ await rm(dir, {
291
+ force: true,
292
+ recursive: true
293
+ });
294
+ }
295
+ }
296
+ //#endregion
297
+ //#region src/sources/github/index.ts
298
+ function normalizeGitHubRoot(path = "") {
299
+ return normalizeSourcePath(path).split("/").filter((part) => part && part !== ".").join("/");
300
+ }
301
+ function dedupeProviderPromise(promises, key, load) {
302
+ const promise = promises.get(key);
303
+ if (promise) return promise;
304
+ const nextPromise = load().finally(() => {
305
+ promises.delete(key);
306
+ });
307
+ promises.set(key, nextPromise);
308
+ return nextPromise;
309
+ }
310
+ function github(options) {
311
+ const configuredRef = options.ref;
312
+ const root = normalizeGitHubRoot(options.root || "");
313
+ const sparsePatterns = getGitSparsePatterns(root, options.include);
314
+ let auth;
315
+ const providerCache = normalizeGitHubCache(options);
316
+ function resolveAuth() {
317
+ const token = typeof options.auth === "function" ? options.auth() : options.auth;
318
+ return typeof token === "string" && token.length > 0 ? token : void 0;
319
+ }
320
+ function refreshAuth() {
321
+ const nextAuth = resolveAuth();
322
+ if (nextAuth !== auth) auth = nextAuth;
323
+ return auth;
324
+ }
325
+ function keyForRepoPath(path) {
326
+ const normalized = normalizeSourcePath(path);
327
+ if (!root) return normalized;
328
+ if (!normalized.startsWith(`${root}/`)) return void 0;
329
+ return normalized.slice(root.length + 1);
330
+ }
331
+ function repoPathForKey(key) {
332
+ const normalized = normalizeSourcePath(key);
333
+ return root ? `${root}/${normalized}` : normalized;
334
+ }
335
+ function contentsUrl(repoPath, ref) {
336
+ return `https://api.github.com/repos/${options.repo}/contents/${encodeURIComponent(repoPath).replace(/%2F/g, "/")}?ref=${encodeURIComponent(ref)}`;
337
+ }
338
+ function shouldInclude(key) {
339
+ if (options.include && !matchesAny(key, options.include)) return false;
340
+ if (options.exclude && matchesAny(key, options.exclude)) return false;
341
+ return true;
342
+ }
343
+ async function resolveRef(token = auth, signal) {
344
+ if (configuredRef) return configuredRef;
345
+ try {
346
+ const defaultBranch = (await requestGitHubJson({
347
+ ref: "default",
348
+ repo: options.repo,
349
+ signal,
350
+ token,
351
+ url: `https://api.github.com/repos/${options.repo}`
352
+ })).default_branch || "main";
353
+ return (await requestGitHubJson({
354
+ ref: defaultBranch,
355
+ repo: options.repo,
356
+ signal,
357
+ token,
358
+ url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(defaultBranch)}`
359
+ })).sha || defaultBranch;
360
+ } catch (error) {
361
+ if (shouldResolveMainFallback(error)) return "main";
362
+ throw error;
363
+ }
364
+ }
365
+ function shouldResolveMainFallback(error) {
366
+ return isSourceError(error) && error instanceof Error && error.message.includes(" request failed with 403 ");
367
+ }
368
+ const resolvedRefs = /* @__PURE__ */ new Map();
369
+ const cachedResolveRef = providerCache ? defineCachedFunction(async (token) => await resolveRef(token), {
370
+ ...providerCache,
371
+ getKey: (token) => cacheKey("ref", token || ""),
372
+ name: "github-source-ref"
373
+ }) : (token) => dedupeProviderPromise(resolvedRefs, cacheKey("ref", token || ""), () => resolveRef(token));
374
+ async function getRef(token = refreshAuth(), signal) {
375
+ return signal ? await resolveRef(token, signal) : await cachedResolveRef(token);
376
+ }
377
+ async function validateConfiguredRef(token = auth, signal) {
378
+ if (!configuredRef) return;
379
+ await requestGitHubJson({
380
+ ref: configuredRef,
381
+ repo: options.repo,
382
+ signal,
383
+ token,
384
+ url: `https://api.github.com/repos/${options.repo}/commits/${encodeURIComponent(configuredRef)}`
385
+ });
386
+ }
387
+ async function loadArchiveFiles(token = auth, signal, resolvedRef) {
388
+ const ref = resolvedRef ?? await getRef(token, signal);
389
+ return parseGitHubArchive(await fetchGitHubArchive({
390
+ ref,
391
+ repo: options.repo,
392
+ signal,
393
+ token
394
+ })).map((entry) => {
395
+ const key = keyForRepoPath(entry.path);
396
+ if (!key || !shouldInclude(key)) return void 0;
397
+ return {
398
+ content: entry.content,
399
+ key,
400
+ path: key,
401
+ ref,
402
+ sha: ref
403
+ };
404
+ }).filter((file) => Boolean(file));
405
+ }
406
+ async function loadFiles(token = auth, signal) {
407
+ const ref = await getRef(token, signal);
408
+ if (sparsePatterns) try {
409
+ return await loadGitArchiveFiles({
410
+ keyForRepoPath,
411
+ ref,
412
+ repo: options.repo,
413
+ shouldInclude,
414
+ signal,
415
+ sparsePatterns,
416
+ token
417
+ });
418
+ } catch (error) {
419
+ if (signal?.aborted) throw error;
420
+ }
421
+ return await loadArchiveFiles(token, signal, ref);
422
+ }
423
+ const loadedFiles = /* @__PURE__ */ new Map();
424
+ const cachedLoadFiles = providerCache ? defineCachedFunction(async (token) => await loadFiles(token), {
425
+ ...providerCache,
426
+ getKey: (token) => cacheKey("archive", token || ""),
427
+ name: "github-source-archive"
428
+ }) : (token) => dedupeProviderPromise(loadedFiles, cacheKey("archive", token || ""), () => loadFiles(token));
429
+ function getFiles(token = refreshAuth(), signal) {
430
+ return signal ? loadFiles(token, signal) : cachedLoadFiles(token);
431
+ }
432
+ async function loadFileMetadata(key, token = auth, signal) {
433
+ const normalizedKey = normalizeSourcePath(key);
434
+ if (!normalizedKey || !shouldInclude(normalizedKey)) return;
435
+ const ref = await getRef(token, signal);
436
+ const repoPath = repoPathForKey(normalizedKey);
437
+ let file;
438
+ try {
439
+ file = await requestGitHubJson({
440
+ ref,
441
+ repo: options.repo,
442
+ signal,
443
+ token,
444
+ url: contentsUrl(repoPath, ref)
445
+ });
446
+ } catch (error) {
447
+ if (isGitHubAccessError(error)) {
448
+ await validateConfiguredRef(token, signal);
449
+ return;
450
+ }
451
+ if (shouldResolveMainFallback(error)) return (signal ? await loadArchiveFiles(token, signal, ref) : await getFiles(token)).find((file) => file.key === normalizedKey);
452
+ throw error;
453
+ }
454
+ if (!file || Array.isArray(file)) return;
455
+ if (file.type === "dir") return;
456
+ return {
457
+ key: normalizedKey,
458
+ path: normalizedKey,
459
+ ref,
460
+ sha: file.sha || ref
461
+ };
462
+ }
463
+ const loadedFileMetadata = /* @__PURE__ */ new Map();
464
+ const cachedLoadFileMetadata = providerCache ? defineCachedFunction(async (key, token) => await loadFileMetadata(key, token), {
465
+ ...providerCache,
466
+ getKey: (key, token) => cacheKey("metadata", token || "", key),
467
+ name: "github-source-metadata"
468
+ }) : (key, token) => dedupeProviderPromise(loadedFileMetadata, cacheKey("metadata", token || "", key), () => loadFileMetadata(key, token));
469
+ function isGitHubAccessError(error) {
470
+ return isSourceError(error) && error instanceof Error && error.message.includes(" could not access the repository or ref ");
471
+ }
472
+ async function loadFile(key, token = auth, signal) {
473
+ const normalizedKey = normalizeSourcePath(key);
474
+ if (!normalizedKey || !shouldInclude(normalizedKey)) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
475
+ const ref = await getRef(token, signal);
476
+ const repoPath = repoPathForKey(normalizedKey);
477
+ const file = await requestGitHubJson({
478
+ ref,
479
+ repo: options.repo,
480
+ signal,
481
+ token,
482
+ url: contentsUrl(repoPath, ref)
483
+ });
484
+ if (Array.isArray(file) || file.type === "dir") throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) expected ${JSON.stringify(key)} to be a file, but it is a directory.`);
485
+ if (file.encoding !== "base64" || typeof file.content !== "string") throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include file content for ${JSON.stringify(key)}.`);
486
+ return {
487
+ content: new Uint8Array(Buffer.from(file.content.replace(/\s/g, ""), "base64")),
488
+ key: normalizedKey,
489
+ path: normalizedKey,
490
+ ref,
491
+ sha: file.sha || ref
492
+ };
493
+ }
494
+ async function getFile(key, ctx, token = refreshAuth()) {
495
+ if (ctx?.abortSignal) return await loadFile(key, token, ctx.abortSignal);
496
+ const file = (await getFiles(token)).find((file) => file.key === key);
497
+ if (!file) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
498
+ return file;
499
+ }
500
+ function fetchContent(key, file) {
501
+ if (file.content) return Promise.resolve(file.content);
502
+ throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include archive content for ${JSON.stringify(key)}.`);
503
+ }
504
+ function cacheKey(kind, token, key = "") {
505
+ return createGitHubCacheKey({
506
+ exclude: options.exclude,
507
+ include: options.include,
508
+ key,
509
+ kind,
510
+ ref: configuredRef || "default",
511
+ repo: options.repo,
512
+ root,
513
+ token
514
+ });
515
+ }
516
+ return {
517
+ cache: options.cache,
518
+ fingerprint: {
519
+ exclude: options.exclude,
520
+ include: options.include,
521
+ ref: configuredRef || "default",
522
+ repo: options.repo,
523
+ root
524
+ },
525
+ name: "github",
526
+ async getKeys(ctx) {
527
+ return (await getFiles(refreshAuth(), ctx.abortSignal)).map((file) => file.key);
528
+ },
529
+ async getItems(ctx) {
530
+ const token = refreshAuth();
531
+ return await Promise.all((await getFiles(token, ctx.abortSignal)).map(async (file) => ({
532
+ key: file.key,
533
+ path: file.path,
534
+ content: await fetchContent(file.key, file),
535
+ metadata: {
536
+ ref: file.ref,
537
+ sha: file.sha
538
+ }
539
+ })));
540
+ },
541
+ async getMeta(key, ctx) {
542
+ const token = refreshAuth();
543
+ const file = ctx?.abortSignal ? await loadFileMetadata(key, token, ctx.abortSignal) : await cachedLoadFileMetadata(key, token);
544
+ if (!file) return;
545
+ return {
546
+ ref: file.ref,
547
+ sha: file.sha
548
+ };
549
+ },
550
+ async getItem(key, ctx) {
551
+ const file = await getFile(key, ctx, refreshAuth());
552
+ return {
553
+ key: file.key,
554
+ path: file.path,
555
+ content: await fetchContent(key, file),
556
+ metadata: {
557
+ ref: file.ref,
558
+ sha: file.sha
559
+ }
560
+ };
561
+ }
562
+ };
563
+ }
564
+ //#endregion
565
+ export { github as t };
@@ -1,4 +1,4 @@
1
- import { r as Source } from "./types-DgWwkKHY.js";
1
+ import { r as Source } from "./types-f6Lyjq8g.js";
2
2
 
3
3
  //#region src/sources/glob.d.ts
4
4
  interface GlobSourceOptions {
@@ -1,11 +1,11 @@
1
- import { i as SourceCacheOptions, r as Source } from "./types-DgWwkKHY.js";
1
+ import { i as SourceCacheOptions, r as Source } from "./types-f6Lyjq8g.js";
2
2
 
3
3
  //#region src/sources/github/types.d.ts
4
4
  interface GitHubSourceOptions {
5
5
  repo: string;
6
6
  ref?: string;
7
7
  root?: string;
8
- auth?: string | (() => string | undefined);
8
+ auth?: false | string | (() => string | undefined);
9
9
  include?: string | string[];
10
10
  exclude?: string | string[];
11
11
  cache?: false | SourceCacheOptions;
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { a as SourceContent, c as SourceKey, d as SourceName, f as SourceReader, i as SourceCacheOptions, l as SourceListEntry, m as SourceSearchQuery, n as ReadSourceResult, o as SourceContext, p as SourceSearchHit, r as Source, s as SourceItem, t as ReadSourceOptions, u as SourceMap } from "./types-DgWwkKHY.js";
2
- import { t as custom } from "./custom-CMmjCoru.js";
3
- import { i as file, n as FileSourceOptions } from "./file-D8j_HGST.js";
4
- import { n as GitHubSourceOptions, t as github } from "./index-ChHHP4I8.js";
5
- import { n as glob, t as GlobSourceOptions } from "./glob-B_tSBNmd.js";
6
- import { t as markdown } from "./markdown-IpYjHOyM.js";
1
+ import { a as SourceContent, c as SourceKey, d as SourceName, f as SourceReader, i as SourceCacheOptions, l as SourceListEntry, m as SourceSearchQuery, n as ReadSourceResult, o as SourceContext, p as SourceSearchHit, r as Source, s as SourceItem, t as ReadSourceOptions, u as SourceMap } from "./types-f6Lyjq8g.js";
2
+ import { t as custom } from "./custom-EnZvMLiy.js";
3
+ import { i as file, n as FileSourceOptions } from "./file-slFAccIZ.js";
4
+ import { n as GitHubSourceOptions, t as github } from "./index-CJpN2j6c.js";
5
+ import { n as glob, t as GlobSourceOptions } from "./glob-CuxZwoC3.js";
6
+ import { t as markdown } from "./markdown-Beo-0cqc.js";
7
+ import { a as McpResourcesRequestOptions, i as McpResourcesClientConfig, l as mcpResources, n as McpResourceDescriptor, o as McpResourcesServer, r as McpResourcesClient, s as McpResourcesSourceOptions, t as McpResourceContent } from "./mcp-resources-C7-5Qeh4.js";
7
8
  import { t as index_d_exports } from "./sources/index.js";
9
+ import { ViteHubError } from "@vite-hub/runtime";
8
10
 
9
11
  //#region src/core/define.d.ts
10
12
  declare function defineSource<const TSource extends Source>(source: TSource): TSource;
@@ -18,14 +20,6 @@ declare function clearSources(): void;
18
20
  declare function useSource<TName extends SourceName>(name: TName, context?: Partial<SourceContext>): SourceReader<TName>;
19
21
  //#endregion
20
22
  //#region src/core/errors.d.ts
21
- declare class SourceError extends Error {
22
- constructor(message: string, options?: ErrorOptions);
23
- }
24
- declare class SourceNotFoundError extends SourceError {
25
- constructor(name: string);
26
- }
27
- declare class SourcePathError extends SourceError {
28
- constructor(path: string);
29
- }
23
+ type SourceErrorCode = "SOURCE_FAILED" | "SOURCE_NOT_FOUND" | "SOURCE_PATH_INVALID";
30
24
  //#endregion
31
- export { type FileSourceOptions, type GitHubSourceOptions, type GlobSourceOptions, ReadSourceOptions, ReadSourceResult, Source, SourceCacheOptions, SourceContent, SourceContext, SourceError, SourceItem, SourceKey, SourceListEntry, SourceMap, SourceName, SourceNotFoundError, SourcePathError, SourceReader, SourceSearchHit, SourceSearchQuery, clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, registerSource, registerSources, index_d_exports as source, useSource };
25
+ export { type FileSourceOptions, type GitHubSourceOptions, type GlobSourceOptions, type McpResourceContent, type McpResourceDescriptor, type McpResourcesClient, type McpResourcesClientConfig, type McpResourcesRequestOptions, type McpResourcesServer, type McpResourcesSourceOptions, type ReadSourceOptions, type ReadSourceResult, type Source, type SourceCacheOptions, type SourceContent, type SourceContext, type SourceErrorCode, type SourceItem, type SourceKey, type SourceListEntry, type SourceMap, type SourceName, type SourceReader, type SourceSearchHit, type SourceSearchQuery, clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, mcpResources, registerSource, registerSources, index_d_exports as source, useSource };
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
- import { a as SourceError, i as normalizeSourcePath, o as SourceNotFoundError, r as normalizeSafeSourcePath, s as SourcePathError, t as decodeSourceContent } from "./path-C0L1l0Fw.js";
1
+ import { i as normalizeSourcePath, o as sourceError, r as normalizeSafeSourcePath, s as sourceNotFoundError, t as decodeSourceContent } from "./path-B5QNI5sY.js";
2
2
  import { custom } from "./sources/custom.js";
3
3
  import { file } from "./sources/file.js";
4
- import { t as github } from "./github-Dp-ghUUj.js";
4
+ import { t as github } from "./github-B4lgrzXQ.js";
5
5
  import { glob } from "./sources/glob.js";
6
6
  import { markdown } from "./sources/markdown.js";
7
+ import { t as mcpResources } from "./mcp-resources-DSDqTfbK.js";
7
8
  import { t as sources_exports } from "./sources/index.js";
8
9
  //#region src/core/define.ts
9
10
  function defineSource(source) {
@@ -25,7 +26,7 @@ function registerSources(sources) {
25
26
  }
26
27
  function getRegisteredSource(name) {
27
28
  const source = sourceRegistry.get(name);
28
- if (!source) throw new SourceNotFoundError(name);
29
+ if (!source) throw sourceNotFoundError(name);
29
30
  return source;
30
31
  }
31
32
  function clearSources() {
@@ -33,6 +34,7 @@ function clearSources() {
33
34
  }
34
35
  function createSourceContext(name, context = {}) {
35
36
  return {
37
+ abortSignal: context.abortSignal,
36
38
  rootDir: context.rootDir || process.cwd(),
37
39
  source: context.source || name,
38
40
  sourceRootDir: context.sourceRootDir,
@@ -40,7 +42,7 @@ function createSourceContext(name, context = {}) {
40
42
  };
41
43
  }
42
44
  function createMissingContentError(key) {
43
- return new SourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
45
+ return sourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
44
46
  }
45
47
  function isNestedUnder(path, prefix) {
46
48
  return !prefix || path === prefix || path.startsWith(`${prefix}/`);
@@ -114,4 +116,4 @@ function useSource(name, context) {
114
116
  };
115
117
  }
116
118
  //#endregion
117
- export { SourceError, SourceNotFoundError, SourcePathError, clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, registerSource, registerSources, sources_exports as source, useSource };
119
+ export { clearSources, custom, defineSource, defineSources, file, getRegisteredSource, github, glob, markdown, mcpResources, registerSource, registerSources, sources_exports as source, useSource };
@@ -1,5 +1,5 @@
1
- import { r as Source } from "./types-DgWwkKHY.js";
2
- import { n as FileSourceOptions } from "./file-D8j_HGST.js";
1
+ import { r as Source } from "./types-f6Lyjq8g.js";
2
+ import { n as FileSourceOptions } from "./file-slFAccIZ.js";
3
3
 
4
4
  //#region src/sources/markdown.d.ts
5
5
  declare function markdown<const TKey extends string = string>(options: FileSourceOptions<TKey>): Source<TKey>;