@vite-hub/source 0.0.0 → 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.
- package/README.md +38 -1
- package/dist/chunk-D7D4PA-g.js +13 -0
- package/dist/custom-EnZvMLiy.d.ts +6 -0
- package/dist/file-slFAccIZ.d.ts +20 -0
- package/dist/github-B4lgrzXQ.js +565 -0
- package/dist/glob-CuxZwoC3.d.ts +15 -0
- package/dist/index-CJpN2j6c.d.ts +17 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +119 -0
- package/dist/markdown-Beo-0cqc.d.ts +7 -0
- package/dist/mcp-resources-C7-5Qeh4.d.ts +41 -0
- package/dist/mcp-resources-DSDqTfbK.js +307 -0
- package/dist/path-B5QNI5sY.js +44 -0
- package/dist/sources/custom.d.ts +2 -0
- package/dist/sources/custom.js +6 -0
- package/dist/sources/file.d.ts +2 -0
- package/dist/sources/file.js +57 -0
- package/dist/sources/github.d.ts +2 -0
- package/dist/sources/github.js +2 -0
- package/dist/sources/glob.d.ts +2 -0
- package/dist/sources/glob.js +110 -0
- package/dist/sources/index.d.ts +13 -0
- package/dist/sources/index.js +18 -0
- package/dist/sources/markdown.d.ts +2 -0
- package/dist/sources/markdown.js +10 -0
- package/dist/sources/mcp-resources.d.ts +2 -0
- package/dist/sources/mcp-resources.js +2 -0
- package/dist/types-f6Lyjq8g.d.ts +73 -0
- package/package.json +87 -5
package/README.md
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
1
|
# @vite-hub/source
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p>
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
|
|
6
|
+
<img alt="Sources" src="https://img.shields.io/badge/Source-typed%20retrieval-0f766e?style=flat-square">
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
`@vite-hub/source` loads files, globs, markdown, GitHub content, or custom data before something else places it in a workspace.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pnpm add @vite-hub/source
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Minimal API
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
// server/utils/sources.ts
|
|
21
|
+
import { defineSources, file, github, glob, registerSources, useSource } from "@vite-hub/source"
|
|
22
|
+
|
|
23
|
+
registerSources(defineSources({
|
|
24
|
+
docs: glob({ include: "docs/**/*.md" }),
|
|
25
|
+
readme: file("README.md"),
|
|
26
|
+
upstream: github({ repo: "vite-hub/vitehub" }),
|
|
27
|
+
}))
|
|
28
|
+
|
|
29
|
+
const docs = useSource("docs", { rootDir: process.cwd() })
|
|
30
|
+
const keys = await docs.keys()
|
|
31
|
+
const first = await docs.read(keys[0]!)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Used by
|
|
35
|
+
|
|
36
|
+
[`@vite-hub/workspace`](../workspace/README.md) materializes Source output into workspace files. Use this package directly when you only need typed source loading and not a workspace file tree.
|
|
37
|
+
|
|
38
|
+
Built on [tinyglobby](https://github.com/SuperchupuDev/tinyglobby), [picomatch](https://github.com/micromatch/picomatch), and [mrmime](https://github.com/lukeed/mrmime).
|
|
39
|
+
|
|
40
|
+
Learn more at [vitehub.dev](https://vitehub.dev).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, no_symbols) => {
|
|
4
|
+
let target = {};
|
|
5
|
+
for (var name in all) __defProp(target, name, {
|
|
6
|
+
get: all[name],
|
|
7
|
+
enumerable: true
|
|
8
|
+
});
|
|
9
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
10
|
+
return target;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { __exportAll as t };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { a as SourceContent, r as Source } from "./types-f6Lyjq8g.js";
|
|
2
|
+
|
|
3
|
+
//#region src/sources/file.d.ts
|
|
4
|
+
interface FileSourcePathOptions<TKey extends string = string> {
|
|
5
|
+
path: string;
|
|
6
|
+
workspacePath?: TKey;
|
|
7
|
+
content?: never;
|
|
8
|
+
mediaType?: string;
|
|
9
|
+
}
|
|
10
|
+
interface FileSourceInlineOptions<TKey extends string = string> {
|
|
11
|
+
workspacePath: TKey;
|
|
12
|
+
content: SourceContent;
|
|
13
|
+
mediaType?: string;
|
|
14
|
+
path?: never;
|
|
15
|
+
}
|
|
16
|
+
type FileSourceOptions<TKey extends string = string> = FileSourcePathOptions<TKey> | FileSourceInlineOptions<TKey>;
|
|
17
|
+
type FileSourceInput<TKey extends string = string> = FileSourceOptions<TKey> | TKey;
|
|
18
|
+
declare function file<const TKey extends string = string>(input: FileSourceInput<TKey>): Source<TKey>;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { file as i, FileSourceOptions as n, FileSourcePathOptions as r, FileSourceInlineOptions as t };
|
|
@@ -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 };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { r as Source } from "./types-f6Lyjq8g.js";
|
|
2
|
+
|
|
3
|
+
//#region src/sources/glob.d.ts
|
|
4
|
+
interface GlobSourceOptions {
|
|
5
|
+
cwd?: string;
|
|
6
|
+
dot?: boolean;
|
|
7
|
+
followSymlinks?: boolean;
|
|
8
|
+
include: string | string[];
|
|
9
|
+
ignore?: string | string[];
|
|
10
|
+
keyCache?: boolean;
|
|
11
|
+
prefix?: string;
|
|
12
|
+
}
|
|
13
|
+
declare function glob<const TKey extends string = string>(options: GlobSourceOptions): Source<TKey>;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { glob as n, GlobSourceOptions as t };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { i as SourceCacheOptions, r as Source } from "./types-f6Lyjq8g.js";
|
|
2
|
+
|
|
3
|
+
//#region src/sources/github/types.d.ts
|
|
4
|
+
interface GitHubSourceOptions {
|
|
5
|
+
repo: string;
|
|
6
|
+
ref?: string;
|
|
7
|
+
root?: string;
|
|
8
|
+
auth?: false | string | (() => string | undefined);
|
|
9
|
+
include?: string | string[];
|
|
10
|
+
exclude?: string | string[];
|
|
11
|
+
cache?: false | SourceCacheOptions;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/sources/github/index.d.ts
|
|
15
|
+
declare function github<const TKey extends string = string>(options: GitHubSourceOptions): Source<TKey>;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { GitHubSourceOptions as n, github as t };
|