@vite-hub/source 0.1.0 → 0.3.1

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 (48) hide show
  1. package/README.md +83 -49
  2. package/dist/client.d.ts +1 -1
  3. package/dist/client.js +30 -4
  4. package/dist/{collection-B_4w_J8h.d.ts → collection-B8sgxw5-.d.ts} +52 -19
  5. package/dist/collection-C0Rvrx3p.js +297 -0
  6. package/dist/drizzle.d.ts +11 -4
  7. package/dist/drizzle.js +6 -8
  8. package/dist/error-diagnostics-ClQKdi7c.js +194 -0
  9. package/dist/github-D5S0dEZe.js +1312 -0
  10. package/dist/{glob-BmFqTvJY.js → glob-DmdMVqjx.js} +1 -2
  11. package/dist/index.d.ts +186 -55
  12. package/dist/index.js +152 -207
  13. package/dist/invariant-DolT9EEx.js +22 -0
  14. package/dist/mcp.d.ts +1 -1
  15. package/dist/mcp.js +25 -140
  16. package/dist/object-CtSHeGQO.js +17 -0
  17. package/dist/{path-BS8rYm0n.js → path-DFlSryRA.js} +32 -2
  18. package/dist/root-DJNmqCEW.js +11 -0
  19. package/dist/server.d.ts +7 -244
  20. package/dist/server.js +38 -45
  21. package/dist/{types-BigOktIj.d.ts → types-Ln-FxVFn.d.ts} +6 -1
  22. package/dist/vite.d.ts +77 -10
  23. package/dist/vite.js +619 -713
  24. package/package.json +25 -47
  25. package/dist/auth-B-tX_rp0.js +0 -1426
  26. package/dist/client-BwstxtdY.js +0 -8280
  27. package/dist/collection-cursor-WzV1Jd6v.js +0 -124
  28. package/dist/error-diagnostics-X0kuFjBT.js +0 -51
  29. package/dist/file-BX0FSvgE.js +0 -60
  30. package/dist/file-DadN9dbN.d.ts +0 -19
  31. package/dist/file.d.ts +0 -2
  32. package/dist/file.js +0 -2
  33. package/dist/files.d.ts +0 -15
  34. package/dist/files.js +0 -38
  35. package/dist/github.d.ts +0 -20
  36. package/dist/github.js +0 -1332
  37. package/dist/glob.d.ts +0 -23
  38. package/dist/glob.js +0 -2
  39. package/dist/markdown.d.ts +0 -5
  40. package/dist/markdown.js +0 -10
  41. package/dist/mrmime-40h5OOIp.js +0 -448
  42. package/dist/path-DOBpV8ol.js +0 -32
  43. package/dist/sse-D9gqqNPj.js +0 -448
  44. package/dist/streamableHttp-BL-E7pl5.js +0 -509
  45. package/dist/types-CoWcW8oz.js +0 -7590
  46. package/tsconfig.vite.json +0 -6
  47. package/types/source/fallback.d.ts +0 -1
  48. package/types/source/index.d.ts +0 -1
package/dist/github.js DELETED
@@ -1,1332 +0,0 @@
1
- import { n as matchesAny } from "./path-BS8rYm0n.js";
2
- import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
3
- import { i as sourceError, n as normalizeSafeSourcePath, r as normalizeSourcePath } from "./path-DOBpV8ol.js";
4
- import { forgeArchive, forgeEnv, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeProvider, readForgeEnv } from "@vite-hub/forge";
5
- import crypto, { createHash } from "node:crypto";
6
- import { Buffer } from "node:buffer";
7
- import { gunzipSync } from "node:zlib";
8
- import { devNull } from "node:os";
9
- //#region ../../node_modules/.pnpm/ocache@0.3.0/node_modules/ocache/lib/digest.node.mjs
10
- /**
11
- * Both forms hash the same bytes: a string is UTF-8 encoded, a `Uint8Array` is hashed as given.
12
- *
13
- * @param {string | Uint8Array} data
14
- * @returns {string} sha256 of `data`, base64url, unpadded.
15
- */
16
- function digest(data) {
17
- return crypto.hash ? crypto.hash("sha256", data, "base64url") : crypto.createHash("sha256").update(data).digest("base64url");
18
- }
19
- //#endregion
20
- //#region ../../node_modules/.pnpm/ocache@0.3.0/node_modules/ocache/dist/index.mjs
21
- const NodeBuffer = globalThis.Buffer;
22
- const hasNativeCodec = typeof Uint8Array.prototype.toBase64 === "function" && typeof Uint8Array.fromBase64 === "function";
23
- const bytesToBase64 = NodeBuffer ? bufferToBase64 : hasNativeCodec ? nativeToBase64 : portableToBase64;
24
- const base64ToBytes = NodeBuffer ? bufferFromBase64 : hasNativeCodec ? nativeFromBase64 : portableFromBase64;
25
- /*#__NO_SIDE_EFFECTS__*/
26
- function bufferToBase64(bytes) {
27
- return NodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
28
- }
29
- /*#__NO_SIDE_EFFECTS__*/
30
- function bufferFromBase64(base64) {
31
- const buffer = NodeBuffer.from(base64, "base64");
32
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
33
- }
34
- /*#__NO_SIDE_EFFECTS__*/
35
- function nativeToBase64(bytes) {
36
- return bytes.toBase64();
37
- }
38
- /*#__NO_SIDE_EFFECTS__*/
39
- function nativeFromBase64(base64) {
40
- return Uint8Array.fromBase64(base64);
41
- }
42
- const CHUNK = 32766;
43
- /*#__NO_SIDE_EFFECTS__*/
44
- function portableToBase64(bytes) {
45
- let base64 = "";
46
- for (let start = 0; start < bytes.length; start += CHUNK) {
47
- const end = Math.min(start + CHUNK, bytes.length);
48
- let binary = "";
49
- for (let i = start; i < end; i++) binary += String.fromCharCode(bytes[i]);
50
- base64 += btoa(binary);
51
- }
52
- return base64;
53
- }
54
- /*#__NO_SIDE_EFFECTS__*/
55
- function portableFromBase64(base64) {
56
- const binary = atob(base64);
57
- const bytes = new Uint8Array(binary.length);
58
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
59
- return bytes;
60
- }
61
- const PREFIX = "[ocache]";
62
- function error(name, message, options) {
63
- const err = new Error(`${PREFIX} ${message}`, options);
64
- err.name = name;
65
- return err;
66
- }
67
- function timeoutError(seconds) {
68
- return error("TimeoutError", `Resolver timed out after ${seconds}s.`);
69
- }
70
- function storageRequiredError(caller) {
71
- return error("StorageRequiredError", `${caller}() requires \`options.storage\`.`);
72
- }
73
- function malformedEntryError() {
74
- return error("MalformedEntryError", "Malformed data read from cache.");
75
- }
76
- function tooDeepError(maxDepth) {
77
- return /* @__PURE__ */ new RangeError(`${PREFIX} Cannot hash a value nested deeper than ${maxDepth} levels. Pass an explicit \`getKey\`.`);
78
- }
79
- const SharedBuffer$1 = globalThis.SharedArrayBuffer;
80
- const MAX_DEPTH = 128;
81
- function hash(input) {
82
- return digest(serialize(input));
83
- }
84
- function serialize(input) {
85
- return typeof input === "string" ? serString(input) : ser(input, /* @__PURE__ */ new Map(), 0);
86
- }
87
- function serString(value) {
88
- return `'${value.length}:${value}`;
89
- }
90
- function serTag(ctor) {
91
- return serString(typeof ctor.name === "string" ? ctor.name : "");
92
- }
93
- function serBytes(bytes) {
94
- return serString(bytesToBase64(bytes));
95
- }
96
- function ser(value, seen, depth) {
97
- if (value === null) return "null";
98
- switch (typeof value) {
99
- case "string": return serString(value);
100
- case "bigint": return `${value}n`;
101
- case "symbol": return value.description === void 0 ? "Symbol()" : `Symbol${serString(value.description)}`;
102
- case "function": return `Function${serString(`${value.name}(${value.length})${Function.prototype.toString.call(value).replace(/\s*\n\s*/g, " ")}`)}`;
103
- case "object": {
104
- const ref = seen.get(value);
105
- if (ref !== void 0) return ref;
106
- if (depth >= MAX_DEPTH) throw tooDeepError(MAX_DEPTH);
107
- seen.set(value, `#${seen.size}`);
108
- const serialized = serObject(value, seen, depth + 1);
109
- seen.set(value, serialized);
110
- return serialized;
111
- }
112
- default: return String(value);
113
- }
114
- }
115
- function serObject(value, seen, depth) {
116
- if (Array.isArray(value)) {
117
- let items = "";
118
- for (let index = 0; index < value.length; index++) items += index === 0 ? ser(value[index], seen, depth) : `,${ser(value[index], seen, depth)}`;
119
- return `[${items}]`;
120
- }
121
- const ctor = value.constructor;
122
- if (ctor === Object || ctor == null) return serProperties("", value, seen, depth);
123
- if (value instanceof Date) return `Date(${Number.isNaN(value.getTime()) ? "null" : value.toISOString()})`;
124
- if (value instanceof RegExp || value instanceof URL || value instanceof URLSearchParams || value instanceof Error) return `${serTag(ctor)}${serString(String(value))}`;
125
- if (value instanceof Headers) {
126
- let items = "";
127
- for (const [name, item] of value) items += `,${serString(name)}:${serString(item)}`;
128
- return `Headers{${items.slice(1)}}`;
129
- }
130
- if (value instanceof Set) {
131
- const parts = [];
132
- for (const item of value) parts.push(ser(item, seen, depth));
133
- return `Set[${parts.sort().join(",")}]`;
134
- }
135
- if (value instanceof Map) {
136
- const parts = [];
137
- for (const [key, item] of value) parts.push(`${ser(key, seen, depth)}:${ser(item, seen, depth)}`);
138
- return `Map{${parts.sort().join(",")}}`;
139
- }
140
- if (value instanceof ArrayBuffer || SharedBuffer$1 && value instanceof SharedBuffer$1) return `${serTag(ctor)}[${serBytes(new Uint8Array(value))}]`;
141
- if (ArrayBuffer.isView(value)) {
142
- const perElement = value.BYTES_PER_ELEMENT;
143
- const items = perElement === void 0 || perElement === 1 ? serBytes(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) : value.join(",");
144
- return `${serTag(ctor)}[${items}]`;
145
- }
146
- return serProperties(serTag(ctor), value, seen, depth);
147
- }
148
- function serProperties(tag, value, seen, depth) {
149
- const toJSON = value.toJSON;
150
- if (typeof toJSON === "function") return `${tag}(${ser(toJSON.call(value), seen, depth)})`;
151
- const keys = Object.keys(value).sort();
152
- let parts = "";
153
- for (let index = 0; index < keys.length; index++) {
154
- const key = keys[index];
155
- parts += index === 0 ? `${serString(key)}:` : `,${serString(key)}:`;
156
- parts += ser(value[key], seen, depth);
157
- }
158
- return `${tag}{${parts}}`;
159
- }
160
- const SharedBuffer = globalThis.SharedArrayBuffer;
161
- const DEFAULT_MEMORY_MAX_SIZE = 1e4;
162
- const DEFAULT_MEMORY_MAX_BYTES = 104857600;
163
- function createMemoryStorage(opts = {}) {
164
- const rawMaxSize = opts.maxSize ?? DEFAULT_MEMORY_MAX_SIZE;
165
- const rawMaxBytes = opts.maxBytes ?? DEFAULT_MEMORY_MAX_BYTES;
166
- const maxSize = Number.isFinite(rawMaxSize) && rawMaxSize > 0 ? rawMaxSize : void 0;
167
- const maxBytes = Number.isFinite(rawMaxBytes) && rawMaxBytes > 0 ? rawMaxBytes : void 0;
168
- const sizeOf = opts.sizeOf;
169
- const map = /* @__PURE__ */ new Map();
170
- const timers = /* @__PURE__ */ new Map();
171
- let totalBytes = 0;
172
- function deleteEntry(key) {
173
- const entry = map.get(key);
174
- if (entry) {
175
- totalBytes -= entry.bytes;
176
- map.delete(key);
177
- }
178
- clearTimer(timers, key);
179
- }
180
- return {
181
- maxEntryBytes: maxBytes,
182
- binary: true,
183
- get(key) {
184
- const entry = map.get(key);
185
- if (!entry) return null;
186
- if (entry.expires && Date.now() > entry.expires) {
187
- deleteEntry(key);
188
- return null;
189
- }
190
- if (maxSize || maxBytes) {
191
- map.delete(key);
192
- map.set(key, entry);
193
- }
194
- return entry.value;
195
- },
196
- set(key, value, opts) {
197
- deleteEntry(key);
198
- if (value === null || value === void 0) return;
199
- let bytes = 0;
200
- if (maxBytes) {
201
- const measured = entryBytes(key, value, sizeOf);
202
- if (measured === void 0 || measured > maxBytes) return;
203
- bytes = measured;
204
- }
205
- const ttlMs = opts?.ttl ? opts.ttl * 1e3 : void 0;
206
- map.set(key, {
207
- value,
208
- expires: ttlMs ? Date.now() + ttlMs : void 0,
209
- bytes
210
- });
211
- totalBytes += bytes;
212
- if (ttlMs) {
213
- const timer = setTimeout(() => {
214
- deleteEntry(key);
215
- }, ttlMs);
216
- if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
217
- timers.set(key, timer);
218
- }
219
- if (maxSize || maxBytes) while (maxSize && map.size > maxSize || maxBytes && totalBytes > maxBytes) {
220
- const oldest = map.keys().next().value;
221
- if (oldest === void 0) break;
222
- deleteEntry(oldest);
223
- }
224
- }
225
- };
226
- }
227
- const ENTRY_OVERHEAD = 64;
228
- const PROPERTY_OVERHEAD = 8;
229
- const MAX_ESTIMATE_DEPTH = 8;
230
- function entryBytes(key, value, sizeOf) {
231
- if (sizeOf) try {
232
- const size = sizeOf(value, key);
233
- if (Number.isFinite(size) && size >= 0) return size;
234
- } catch {}
235
- try {
236
- return estimateBytes(key) + ENTRY_OVERHEAD + estimateValue(value, 0, /* @__PURE__ */ new Set());
237
- } catch {
238
- return;
239
- }
240
- }
241
- function estimateBytes(str) {
242
- return str.length * 2;
243
- }
244
- function estimateValue(value, depth, seen) {
245
- switch (typeof value) {
246
- case "string": return estimateBytes(value);
247
- case "number":
248
- case "bigint": return 8;
249
- case "boolean": return 4;
250
- case "object": break;
251
- default: return 0;
252
- }
253
- if (value === null || seen.has(value) || depth >= MAX_ESTIMATE_DEPTH) return 0;
254
- seen.add(value);
255
- if (ArrayBuffer.isView(value)) {
256
- const buffer = value.buffer;
257
- if (seen.has(buffer)) return 0;
258
- seen.add(buffer);
259
- return buffer.byteLength;
260
- }
261
- if (isBuffer(value)) return value.byteLength;
262
- const next = depth + 1;
263
- let total = 0;
264
- if (Array.isArray(value) || value instanceof Set) for (const item of value) total += PROPERTY_OVERHEAD + estimateValue(item, next, seen);
265
- else if (value instanceof Map) for (const [k, v] of value) total += PROPERTY_OVERHEAD + estimateValue(k, next, seen) + estimateValue(v, next, seen);
266
- else for (const key of Object.keys(value)) total += PROPERTY_OVERHEAD + estimateBytes(key) + estimateValue(value[key], next, seen);
267
- return total;
268
- }
269
- function isBuffer(value) {
270
- return value instanceof ArrayBuffer || SharedBuffer !== void 0 && value instanceof SharedBuffer;
271
- }
272
- function clearTimer(timers, key) {
273
- const existing = timers.get(key);
274
- if (existing !== void 0) {
275
- clearTimeout(existing);
276
- timers.delete(key);
277
- }
278
- }
279
- function resolveStorage(...optsList) {
280
- const configured = optsList[0]?.storage;
281
- const storage = (typeof configured === "function" ? configured() : configured) ?? createMemoryStorage();
282
- for (const opts of optsList) if (opts) opts.storage = storage;
283
- return storage;
284
- }
285
- function defaultCacheOptions() {
286
- return {
287
- name: "_",
288
- base: "/cache",
289
- swr: false,
290
- maxAge: 1
291
- };
292
- }
293
- const DEFAULT_MAX_RESOLVE_TIME = 30;
294
- let fences;
295
- let resolveSignals;
296
- let resolveStatuses;
297
- function fencePending(cachedFn, key) {
298
- return fences?.get(cachedFn)?.(key);
299
- }
300
- function defineCachedFunction(fn, opts = {}) {
301
- const name = resolveName(opts.name, fn);
302
- const _optsRef = opts;
303
- opts = {
304
- ...defaultCacheOptions(),
305
- ...definedOptions(opts),
306
- name
307
- };
308
- const getStorage = () => resolveStorage(_optsRef, opts);
309
- const pending = /* @__PURE__ */ new Map();
310
- const releasePending = (key, current) => {
311
- if (pending.get(key) === current) pending.delete(key);
312
- };
313
- const writes = /* @__PURE__ */ new Map();
314
- const trackWrite = (key, write) => {
315
- const earlier = writes.get(key);
316
- const tracked = earlier ? earlier.then(() => write) : write;
317
- writes.set(key, tracked);
318
- tracked.then(() => {
319
- if (writes.get(key) === tracked) writes.delete(key);
320
- });
321
- return tracked;
322
- };
323
- const group = opts.group || "functions";
324
- const integrity = opts.integrity || hash([fn, integrityOpts$1(opts)]);
325
- const validate = opts.validate || ((entry) => entry.value !== void 0);
326
- const rawMaxResolveTime = opts.maxResolveTime ?? DEFAULT_MAX_RESOLVE_TIME;
327
- const maxResolveTime = Number.isFinite(rawMaxResolveTime) && rawMaxResolveTime > 0 ? rawMaxResolveTime : void 0;
328
- const onError = (context, error) => {
329
- if (opts.onError) opts.onError(error);
330
- else console.error(context, error);
331
- };
332
- async function get(key, resolver, args, shouldInvalidateCache, event) {
333
- const validateCtx = { args };
334
- const waitUntil = (promise) => {
335
- if (opts.waitUntil) opts.waitUntil(promise);
336
- else event?.req.waitUntil?.(promise);
337
- };
338
- const bases = normalizeBases(opts.base);
339
- let entry = {};
340
- let hitIndex = -1;
341
- try {
342
- for (let i = 0; i < bases.length; i++) {
343
- const result = await getStorage().get(buildCacheKey(key, {
344
- group,
345
- name
346
- }, bases[i]));
347
- if (result) {
348
- entry = result;
349
- hitIndex = i;
350
- break;
351
- }
352
- }
353
- } catch (error) {
354
- onError("[cache] Cache read error.", error);
355
- }
356
- if (typeof entry !== "object") {
357
- entry = {};
358
- const error = malformedEntryError();
359
- onError("[cache]", error);
360
- } else {
361
- entry = { ...entry };
362
- decodeBinary(entry);
363
- entry.payload = void 0;
364
- }
365
- const readMaxAge = entry.maxAge ?? opts.maxAge;
366
- const readStaleMaxAge = entry.staleMaxAge ?? opts.staleMaxAge;
367
- const ttl = (readMaxAge ?? 0) * 1e3;
368
- if (ttl > 0) entry.expires = Date.now() + ttl;
369
- const staleTtl = opts.swr && readStaleMaxAge != null && readStaleMaxAge >= 0 ? readStaleMaxAge * 1e3 : void 0;
370
- const swr = opts.swr && staleTtl !== 0;
371
- const isFullyExpired = staleTtl !== void 0 && readMaxAge != null && Date.now() - (entry.mtime || 0) > ttl + staleTtl;
372
- const _isValid = await validate(entry, validateCtx) !== false;
373
- const isMatched = entry.integrity === integrity;
374
- const expired = shouldInvalidateCache || entry.stale === true || !isMatched || readMaxAge === 0 || ttl > 0 && Date.now() - (entry.mtime || 0) > ttl || !_isValid;
375
- if (isFullyExpired) {
376
- entry.value = void 0;
377
- entry.integrity = void 0;
378
- entry.mtime = void 0;
379
- entry.expires = void 0;
380
- }
381
- const status = entry.value === void 0 ? "miss" : !expired ? "hit" : swr && _isValid && isMatched ? "stale" : "revalidated";
382
- const resolveEntry = async () => {
383
- let current = pending.get(key);
384
- const isPending = current !== void 0;
385
- if (!current) {
386
- if (entry.value !== void 0 && (opts.staleMaxAge || 0) >= 0 && opts.swr === false) {
387
- entry.value = void 0;
388
- entry.integrity = void 0;
389
- entry.mtime = void 0;
390
- entry.expires = void 0;
391
- }
392
- const controller = maxResolveTime ? new AbortController() : void 0;
393
- if (controller && event) (resolveSignals ??= /* @__PURE__ */ new WeakMap()).set(event, controller.signal);
394
- if (event && status !== "stale") (resolveStatuses ??= /* @__PURE__ */ new WeakMap()).set(event, status);
395
- const resolution = (async () => {
396
- const value = await resolver();
397
- const resolvedEntry = {
398
- value,
399
- mtime: Date.now(),
400
- integrity
401
- };
402
- let maxAge;
403
- let staleMaxAge;
404
- if (opts.getMaxAge) try {
405
- const resolved = await opts.getMaxAge(resolvedEntry);
406
- const dynamic = typeof resolved === "number" ? { maxAge: resolved } : resolved;
407
- maxAge = clampTtl(dynamic?.maxAge);
408
- staleMaxAge = clampTtl(dynamic?.staleMaxAge);
409
- resolvedEntry.maxAge = maxAge;
410
- resolvedEntry.staleMaxAge = staleMaxAge;
411
- } catch (error) {
412
- onError("[cache] getMaxAge hook error.", error);
413
- }
414
- return {
415
- value: normalizeBinary(opts.serialize ? await opts.serialize(resolvedEntry, validateCtx) : value),
416
- maxAge,
417
- staleMaxAge
418
- };
419
- })();
420
- current = { promise: maxResolveTime ? withDeadline(resolution, maxResolveTime, controller) : resolution };
421
- pending.set(key, current);
422
- }
423
- let resolved;
424
- try {
425
- resolved = await current.promise;
426
- } catch (error) {
427
- if (!isPending) {
428
- releasePending(key, current);
429
- if (!current.fenced) {
430
- const evictPromise = evictFromStorage(getStorage(), key, bases, group, name).catch((error) => {
431
- onError("[cache] Cache eviction error.", error);
432
- });
433
- waitUntil(evictPromise);
434
- }
435
- }
436
- throw error;
437
- }
438
- entry.value = resolved.value;
439
- if (!isPending) {
440
- entry.mtime = Date.now();
441
- entry.integrity = integrity;
442
- entry.stale = void 0;
443
- if (opts.getMaxAge) {
444
- entry.maxAge = resolved.maxAge;
445
- entry.staleMaxAge = resolved.staleMaxAge;
446
- }
447
- const setOpts = storageTtl(entry.maxAge ?? opts.maxAge, entry.staleMaxAge ?? opts.staleMaxAge, opts.swr);
448
- try {
449
- const isValid = await validate(entry, validateCtx) !== false;
450
- if (current.fenced) return;
451
- if (isValid && setOpts !== false) {
452
- const writeBases = hitIndex < 0 ? bases : bases.slice(0, hitIndex + 1);
453
- const { status: _status, ...rest } = entry;
454
- const toStore = encodeBinary(rest, getStorage());
455
- const payload = opts.payload ?? (toStore.encoding ? "value" : void 0);
456
- if (payload) toStore.payload = payload;
457
- const promise = (async () => {
458
- try {
459
- await Promise.all(writeBases.map((b) => getStorage().set(buildCacheKey(key, {
460
- group,
461
- name
462
- }, b), toStore, setOpts)));
463
- } catch (error) {
464
- onError("[cache] Cache write error.", error);
465
- }
466
- })();
467
- trackWrite(key, promise);
468
- waitUntil(promise);
469
- } else if (hitIndex >= 0) {
470
- const evictPromise = evictFromStorage(getStorage(), key, bases, group, name).catch((error) => {
471
- onError("[cache] Cache eviction error.", error);
472
- });
473
- waitUntil(evictPromise);
474
- }
475
- } finally {
476
- releasePending(key, current);
477
- }
478
- }
479
- };
480
- const _resolvePromise = expired ? resolveEntry() : Promise.resolve();
481
- if (entry.value === void 0) await _resolvePromise;
482
- else if (expired) waitUntil(_resolvePromise);
483
- Object.defineProperty(entry, "status", {
484
- value: status,
485
- enumerable: false,
486
- writable: true,
487
- configurable: true
488
- });
489
- if (swr && isMatched && await validate(entry, validateCtx) !== false) {
490
- _resolvePromise.catch((error) => {
491
- onError("[cache] SWR handler error.", error);
492
- });
493
- return entry;
494
- }
495
- return _resolvePromise.then(() => entry);
496
- }
497
- const cachedFn = async (...args) => {
498
- if (await opts.shouldBypassCache?.(...args)) return fn(...args);
499
- const entry = await get(await (opts.getKey || getKey)(...args), () => fn(...args), args, await opts.shouldInvalidateCache?.(...args), isHTTPEvent(args[0]) ? args[0] : void 0);
500
- let value = entry.value;
501
- if (opts.transform) value = await opts.transform(entry, ...args) ?? value;
502
- return value;
503
- };
504
- (fences ??= /* @__PURE__ */ new WeakMap()).set(cachedFn, (key) => {
505
- const current = pending.get(key);
506
- if (current) {
507
- current.fenced = true;
508
- pending.delete(key);
509
- }
510
- return writes.get(key);
511
- });
512
- const purgeOptions = async (args) => {
513
- getStorage();
514
- const key = await (opts.getKey || getKey)(...args);
515
- await fencePending(cachedFn, key);
516
- return {
517
- ...opts,
518
- getKey: () => key
519
- };
520
- };
521
- cachedFn.resolveKeys = (...args) => resolveCacheKeys({
522
- options: opts,
523
- args
524
- });
525
- cachedFn.invalidate = async (...args) => {
526
- await invalidateCache({ options: await purgeOptions(args) });
527
- };
528
- cachedFn.expire = async (...args) => {
529
- await expireCache({ options: await purgeOptions(args) });
530
- };
531
- return cachedFn;
532
- }
533
- async function resolveCacheKeys(input = {}) {
534
- const opts = input.options ?? {};
535
- const args = input.args ?? [];
536
- const key = await (opts.getKey || getKey)(...args);
537
- return normalizeBases(opts.base).map((base) => buildCacheKey(key, opts, base));
538
- }
539
- async function invalidateCache(input = {}) {
540
- const keys = await resolveCacheKeys(input);
541
- const storage = requireStorage(input.options, "invalidateCache");
542
- await Promise.all(keys.map((key) => storage.set(key, null)));
543
- }
544
- async function expireCache(input = {}) {
545
- const opts = input.options ?? {};
546
- const keys = await resolveCacheKeys(input);
547
- const storage = requireStorage(opts, "expireCache");
548
- await Promise.all(keys.map(async (key) => {
549
- const entry = await storage.get(key);
550
- if (!entry || typeof entry !== "object" || entry.value === void 0) return;
551
- await storage.set(key, {
552
- ...entry,
553
- stale: true
554
- }, remainingTtl(entry, opts));
555
- }));
556
- }
557
- function resolveName(name, fn) {
558
- return name || fn.name || `anon_${hash(fn).slice(0, 16)}`;
559
- }
560
- function definedOptions(opts) {
561
- const cleaned = { ...opts };
562
- for (const key of Object.keys(cleaned)) if (cleaned[key] === void 0) delete cleaned[key];
563
- return cleaned;
564
- }
565
- function requireStorage(options, caller) {
566
- if (!options?.storage) throw storageRequiredError(caller);
567
- return resolveStorage(options);
568
- }
569
- function withDeadline(work, seconds, controller) {
570
- return new Promise((resolve, reject) => {
571
- const timer = setTimeout(() => {
572
- const error = timeoutError(seconds);
573
- reject(error);
574
- controller?.abort(error);
575
- }, seconds * 1e3);
576
- if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
577
- work.then((value) => {
578
- clearTimeout(timer);
579
- resolve(value);
580
- }, (error) => {
581
- clearTimeout(timer);
582
- reject(error);
583
- });
584
- });
585
- }
586
- function isHTTPEvent(input) {
587
- return input?.req instanceof Request;
588
- }
589
- function clampTtl(value) {
590
- return value == null || !Number.isFinite(value) ? void 0 : Math.max(0, value);
591
- }
592
- function normalizeBinary(value) {
593
- if (value instanceof Uint8Array) return value;
594
- if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
595
- return value instanceof ArrayBuffer ? new Uint8Array(value) : value;
596
- }
597
- function encodeBinary(entry, storage) {
598
- const value = entry.value;
599
- if (!(value instanceof Uint8Array)) return entry;
600
- return storage.binary ? {
601
- ...entry,
602
- encoding: "bytes"
603
- } : {
604
- ...entry,
605
- value: bytesToBase64(value),
606
- encoding: "base64"
607
- };
608
- }
609
- function decodeBinary(entry) {
610
- const encoding = entry.encoding;
611
- if (encoding === void 0) return;
612
- entry.encoding = void 0;
613
- if (encoding === "base64" && typeof entry.value === "string") {
614
- entry.value = base64ToBytes(entry.value);
615
- return;
616
- }
617
- if (encoding === "bytes" && ArrayBuffer.isView(entry.value)) {
618
- entry.value = normalizeBinary(entry.value);
619
- return;
620
- }
621
- entry.value = void 0;
622
- }
623
- function getKey(...args) {
624
- return args.length > 0 ? hash(args) : "";
625
- }
626
- function buildCacheKey(key, opts, base) {
627
- return [
628
- base,
629
- escapeKeySegment(opts.group || "functions"),
630
- escapeKeySegment(opts.name || "_"),
631
- key + ".json"
632
- ].filter(Boolean).join(":").replace(/:\/$/, ":index");
633
- }
634
- function escapeKeySegment(raw) {
635
- const escaped = escapeKey(raw);
636
- return escaped === raw ? escaped : `${escaped.slice(0, 64)}.${hash(raw)}`;
637
- }
638
- function escapeKey(key) {
639
- return String(key).replace(/\W/g, "");
640
- }
641
- function normalizeBases(base) {
642
- if (Array.isArray(base)) return base;
643
- return [base ?? "/cache"];
644
- }
645
- async function evictFromStorage(storage, key, bases, group, name) {
646
- await Promise.all(bases.map((b) => storage.set(buildCacheKey(key, {
647
- group,
648
- name
649
- }, b), null)));
650
- }
651
- function storageTtl(maxAge, staleMaxAge, swr) {
652
- if (maxAge == null || maxAge <= 0) return false;
653
- if (!swr) return { ttl: maxAge };
654
- return staleMaxAge != null && staleMaxAge >= 0 ? { ttl: maxAge + staleMaxAge } : void 0;
655
- }
656
- function remainingTtl(entry, opts) {
657
- const ttlOpts = storageTtl(entry.maxAge ?? opts.maxAge, entry.staleMaxAge ?? opts.staleMaxAge, opts.swr);
658
- if (!entry.mtime || !ttlOpts) return;
659
- return { ttl: Math.max(Math.ceil((entry.mtime + ttlOpts.ttl * 1e3 - Date.now()) / 1e3), 1) };
660
- }
661
- function integrityOpts$1(opts) {
662
- const { base: _, group: _g, name: _n, storage: _s, waitUntil: _w, ...rest } = opts;
663
- return rest;
664
- }
665
- //#endregion
666
- //#region src/sources/github/archive.ts
667
- function parseGitHubArchive(bytes) {
668
- const tar = gunzipSync(bytes);
669
- const files = [];
670
- let offset = 0;
671
- let paxPath;
672
- while (offset + 512 <= tar.length) {
673
- const header = tar.subarray(offset, offset + 512);
674
- if (header.every((byte) => byte === 0)) break;
675
- const name = readTarString(header, 0, 100);
676
- const prefix = readTarString(header, 345, 155);
677
- const path = paxPath || [prefix, name].filter(Boolean).join("/");
678
- const sizeField = readTarString(header, 124, 12).trim();
679
- if (sizeField && !/^[0-7]+$/.test(sizeField)) throw new Error("Invalid GitHub archive entry size.");
680
- const size = sizeField ? Number.parseInt(sizeField, 8) : 0;
681
- if (!Number.isSafeInteger(size) || size < 0) throw new Error("Invalid GitHub archive entry size.");
682
- const type = String.fromCharCode(header[156] || 0);
683
- const contentStart = offset + 512;
684
- const contentEnd = contentStart + size;
685
- const entryEnd = contentStart + Math.ceil(size / 512) * 512;
686
- if (entryEnd > tar.length) throw new Error("Invalid GitHub archive entry size.");
687
- const content = tar.subarray(contentStart, contentEnd);
688
- if (type === "x") paxPath = readPaxPath(content);
689
- else {
690
- if (type === "0" || type === "\0") {
691
- const entryPath = stripArchiveRoot(path);
692
- if (entryPath) files.push({
693
- content: new Uint8Array(content),
694
- path: entryPath
695
- });
696
- }
697
- paxPath = void 0;
698
- }
699
- offset = entryEnd;
700
- }
701
- return files;
702
- }
703
- function readTarString(buffer, offset, length) {
704
- const slice = buffer.subarray(offset, offset + length);
705
- const end = slice.indexOf(0);
706
- return Buffer.from(end === -1 ? slice : slice.subarray(0, end)).toString("utf8");
707
- }
708
- function readPaxPath(content) {
709
- let index = 0;
710
- while (index < content.length) {
711
- let space = index;
712
- while (space < content.length && content[space] !== 32) space++;
713
- if (space >= content.length) return;
714
- const length = Number.parseInt(Buffer.from(content.subarray(index, space)).toString("ascii"), 10);
715
- if (!Number.isFinite(length) || length <= 0 || index + length > content.length) return;
716
- const record = content.subarray(space + 1, index + length - 1);
717
- const equals = record.indexOf(61);
718
- if (equals !== -1 && Buffer.from(record.subarray(0, equals)).toString("utf8") === "path") return Buffer.from(record.subarray(equals + 1)).toString("utf8");
719
- index += length;
720
- }
721
- }
722
- function stripArchiveRoot(path) {
723
- try {
724
- normalizeSafeSourcePath(path);
725
- const slash = path.indexOf("/");
726
- if (slash === -1) return;
727
- return normalizeSafeSourcePath(path.slice(slash + 1));
728
- } catch {
729
- return;
730
- }
731
- }
732
- //#endregion
733
- //#region src/sources/github/cache.ts
734
- function normalizeGitHubCache(options) {
735
- if (options.cache === false) return;
736
- if (options.cache && typeof options.cache === "object") return { maxAge: options.cache.maxAge };
737
- }
738
- function createGitHubCacheKey(input) {
739
- return JSON.stringify([
740
- input.kind,
741
- input.repo,
742
- input.ref,
743
- input.root,
744
- input.include ?? null,
745
- input.ignore ?? null,
746
- input.authScope,
747
- input.key || ""
748
- ]);
749
- }
750
- function githubAuthenticationScope(token) {
751
- return token ? createHash("sha256").update(token).digest("hex") : "anonymous";
752
- }
753
- //#endregion
754
- //#region src/sources/github/client.ts
755
- /** The Server Env token: `VITEHUB_GITHUB_TOKEN`, then `FORGES_GITHUB_TOKEN`. */
756
- function githubEnvToken() {
757
- return readForgeEnv(forgeEnv.github.token);
758
- }
759
- /** The HTTP status of the Forge request behind a GitHub Source error. */
760
- function githubErrorStatus(error) {
761
- return error instanceof Error ? forgeErrorStatus(error.cause) : void 0;
762
- }
763
- function isRecord(value) {
764
- return value !== null && typeof value === "object" && !Array.isArray(value);
765
- }
766
- function isNonEmptyString(value) {
767
- return typeof value === "string" && value.length > 0;
768
- }
769
- function malformed(repo, description) {
770
- return sourceError(`[vitehub] github(${JSON.stringify(repo)}) returned a malformed ${description} response.`);
771
- }
772
- function createGitHubClient(repo) {
773
- const [owner, name, ...rest] = repo.split("/");
774
- let cached;
775
- function provider(token) {
776
- if (!cached || cached.token !== token) cached = {
777
- provider: forgeProvider({
778
- forge: "github",
779
- readOnly: true,
780
- token,
781
- userAgent: "vitehub-source"
782
- }),
783
- token
784
- };
785
- return cached.provider;
786
- }
787
- async function request(ref, description, token, signal, load) {
788
- if (!owner || !name || rest.length) throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) supports GitHub.com repositories only and expects repo as "owner/name".`);
789
- const client = await provider(token);
790
- try {
791
- return await load(client, {
792
- forge: client.forge,
793
- instance: client.instance,
794
- name,
795
- owner
796
- });
797
- } catch (error) {
798
- if (signal?.aborted) throw error;
799
- const status = forgeErrorStatus(error);
800
- if (status === void 0) throw error;
801
- if (status === 404) throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) could not access the repository or ref ${JSON.stringify(ref)}. Check that the repo exists, the ref exists, and auth can access it.`, { cause: error });
802
- throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) ${description} request failed with ${status}.`, { cause: error });
803
- }
804
- }
805
- return {
806
- async archive(ref, token, signal) {
807
- const download = (archiveToken) => request(ref, "archive", archiveToken, signal, async (client, repoRef) => {
808
- const stream = await forgeArchive(client, repoRef, {
809
- ref,
810
- signal
811
- });
812
- return new Uint8Array(await new Response(stream).arrayBuffer());
813
- });
814
- try {
815
- return await download(token);
816
- } catch (error) {
817
- const status = githubErrorStatus(error);
818
- if (!token || status !== 403 && status !== 429) throw error;
819
- return await download(void 0);
820
- }
821
- },
822
- async defaultBranch(token, signal) {
823
- const branch = await request("default", "repository", token, signal, async (client, repoRef) => (await client.repos.get(repoRef, { signal })).defaultBranch);
824
- if (!branch) throw malformed(repo, "repository");
825
- return branch;
826
- },
827
- async file(path, ref, token, signal) {
828
- try {
829
- const file = await request(ref, "content", token, signal, async (client, repoRef) => await client.contents.getFile(repoRef, path, {
830
- ref,
831
- signal
832
- }));
833
- if (file.encoding !== "binary") throw malformed(repo, "content");
834
- return {
835
- content: file.content,
836
- sha: file.sha
837
- };
838
- } catch (error) {
839
- if (githubErrorStatus(error) !== 422) throw error;
840
- throw sourceError(`[vitehub] github(${JSON.stringify(repo)}) expected ${JSON.stringify(path)} to be a file, but GitHub returned a directory or another entry type.`, { cause: error });
841
- }
842
- },
843
- async metadata(path, ref, token, signal) {
844
- const entry = await request(ref, "content", token, signal, async (client, repoRef) => (await client.request("GET", `/repos/${encodeURIComponent(repoRef.owner)}/${encodeURIComponent(repoRef.name)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, {
845
- query: { ref },
846
- signal
847
- })).data);
848
- if (Array.isArray(entry)) return;
849
- if (!isRecord(entry) || !isNonEmptyString(entry.type) || !isNonEmptyString(entry.sha)) throw malformed(repo, "content");
850
- return entry.type === "file" ? { sha: entry.sha } : void 0;
851
- },
852
- async resolveCommit(ref, token, signal) {
853
- const sha = await request(ref, "commit", token, signal, async (client, repoRef) => await client.contents.resolveRef(repoRef, ref, { signal }));
854
- if (typeof sha !== "string" || !sha) throw malformed(repo, "commit");
855
- return sha;
856
- }
857
- };
858
- }
859
- //#endregion
860
- //#region src/sources/github/git.ts
861
- function createGitEnv(home, credentials, baseEnv = process.env) {
862
- const env = { ...baseEnv };
863
- for (const key of [
864
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
865
- "GIT_COMMON_DIR",
866
- "GIT_CONFIG",
867
- "GIT_CONFIG_COUNT",
868
- "GIT_CONFIG_PARAMETERS",
869
- "GIT_DIR",
870
- "GIT_GRAFT_FILE",
871
- "GIT_IMPLICIT_WORK_TREE",
872
- "GIT_INDEX_FILE",
873
- "GIT_NO_REPLACE_OBJECTS",
874
- "GIT_OBJECT_DIRECTORY",
875
- "GIT_PREFIX",
876
- "GIT_REPLACE_REF_BASE",
877
- "GIT_SHALLOW_FILE",
878
- "GIT_WORK_TREE"
879
- ]) delete env[key];
880
- for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(key)) delete env[key];
881
- const authHeader = forgeGitAuthHeader(credentials);
882
- Object.assign(env, {
883
- GCM_INTERACTIVE: "Never",
884
- GIT_ASKPASS: "",
885
- GIT_CONFIG_COUNT: authHeader ? "1" : "0",
886
- GIT_CONFIG_GLOBAL: devNull,
887
- GIT_CONFIG_NOSYSTEM: "1",
888
- GIT_TERMINAL_PROMPT: "0",
889
- HOME: home,
890
- SSH_ASKPASS: "",
891
- USERPROFILE: home,
892
- XDG_CONFIG_HOME: home
893
- });
894
- if (!authHeader) return env;
895
- env.GIT_CONFIG_KEY_0 = authHeader.key;
896
- env.GIT_CONFIG_VALUE_0 = authHeader.value;
897
- return env;
898
- }
899
- async function runGit(args, options = {}) {
900
- const { spawn } = await import("node:child_process");
901
- return await new Promise((resolve, reject) => {
902
- const child = spawn("git", args, {
903
- env: options.env,
904
- signal: options.signal,
905
- stdio: [
906
- "pipe",
907
- "pipe",
908
- "pipe"
909
- ]
910
- });
911
- const stdout = [];
912
- child.stdout.on("data", (chunk) => stdout.push(chunk));
913
- child.stderr.resume();
914
- child.stdin.on("error", () => {});
915
- child.stdin.end();
916
- child.on("error", reject);
917
- child.on("close", (code) => {
918
- if (code === 0) {
919
- resolve(Buffer.concat(stdout));
920
- return;
921
- }
922
- const command = args[0] === "-C" ? args[2] : args[0];
923
- reject(sourceErrorDiagnostics.SOURCE_R0019({ message: `git ${command || "command"} exited with ${code ?? "an unknown status"}.` }));
924
- });
925
- });
926
- }
927
- function isGitSparsePattern(pattern) {
928
- if (pattern.includes("\0") || pattern.includes("\r") || pattern.includes("\n")) return false;
929
- if (pattern.split("/").some((segment) => segment === "." || segment === "..")) return false;
930
- if (!pattern.includes("*")) return !/[?[\]{}()!+@]/.test(pattern);
931
- if (!pattern.endsWith("/**")) return false;
932
- return !/[*?[\]{}()!+@]/.test(pattern.slice(0, -3));
933
- }
934
- function getGitSparsePatterns(root, include) {
935
- const patterns = (include ? Array.isArray(include) ? include : [include] : []).map((pattern) => [root, normalizeSourcePath(pattern)].filter(Boolean).join("/")).filter(Boolean);
936
- if (patterns.some((pattern) => !isGitSparsePattern(pattern))) return;
937
- if (patterns.length) return [...new Set(patterns)];
938
- return root && isGitSparsePattern(root) ? [`${root}/**`] : void 0;
939
- }
940
- function isGitLfsPointer(content) {
941
- if (content.byteLength > 65536) return false;
942
- const lines = Buffer.from(content).toString("utf8").split(/\r?\n/);
943
- 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));
944
- }
945
- async function readGitArchiveFiles(dir, input, executeGit, options) {
946
- input.signal?.throwIfAborted();
947
- const archive = await executeGit([
948
- "-C",
949
- dir,
950
- "archive",
951
- "--format=tar.gz",
952
- "--prefix=archive/",
953
- input.sha,
954
- "--",
955
- ...input.sparsePatterns.map((pattern) => {
956
- return `:(literal)${pattern.endsWith("/**") ? pattern.slice(0, -3) : pattern}`;
957
- })
958
- ], options);
959
- return parseGitHubArchive(Buffer.from(archive)).map((entry) => {
960
- const key = input.keyForRepoPath(entry.path);
961
- if (!key || !input.shouldInclude(key)) return;
962
- if (isGitLfsPointer(entry.content)) throw sourceErrorDiagnostics.SOURCE_R0020({ message: "git archive contained a Git LFS pointer; use the GitHub archive instead." });
963
- return {
964
- content: entry.content,
965
- key,
966
- path: key,
967
- ref: input.ref,
968
- sha: input.sha
969
- };
970
- }).filter((file) => Boolean(file));
971
- }
972
- async function loadGitArchiveFiles(input, executeGit = runGit) {
973
- const [{ mkdtemp, rm }, { tmpdir }, { join }] = await Promise.all([
974
- import("node:fs/promises"),
975
- import("node:os"),
976
- import("node:path")
977
- ]);
978
- const dir = await mkdtemp(join(tmpdir(), "vitehub-github-"));
979
- try {
980
- const options = {
981
- env: createGitEnv(dir, input.credentials, input.env),
982
- signal: input.signal
983
- };
984
- await executeGit([
985
- "init",
986
- "--quiet",
987
- dir
988
- ], options);
989
- await executeGit([
990
- "-C",
991
- dir,
992
- "remote",
993
- "add",
994
- "origin",
995
- input.credentials.url
996
- ], options);
997
- await executeGit([
998
- "-C",
999
- dir,
1000
- "config",
1001
- "remote.origin.promisor",
1002
- "true"
1003
- ], options);
1004
- await executeGit([
1005
- "-C",
1006
- dir,
1007
- "config",
1008
- "remote.origin.partialclonefilter",
1009
- "blob:none"
1010
- ], options);
1011
- await executeGit([
1012
- "-C",
1013
- dir,
1014
- "fetch",
1015
- "--depth=1",
1016
- "--filter=blob:none",
1017
- "--no-tags",
1018
- "--",
1019
- "origin",
1020
- `+${input.ref}`
1021
- ], options);
1022
- const sha = Buffer.from(await executeGit([
1023
- "-C",
1024
- dir,
1025
- "rev-parse",
1026
- "FETCH_HEAD"
1027
- ], options)).toString("utf8").trim();
1028
- return await readGitArchiveFiles(dir, {
1029
- ...input,
1030
- sha
1031
- }, executeGit, options);
1032
- } finally {
1033
- await rm(dir, {
1034
- force: true,
1035
- recursive: true
1036
- });
1037
- }
1038
- }
1039
- //#endregion
1040
- //#region src/sources/github/index.ts
1041
- function normalizeGitHubRoot(path = "") {
1042
- const root = path.replace(/\\/g, "/").split("/").filter((part) => part !== ".").join("/");
1043
- return normalizeSafeSourcePath(root, {
1044
- allowEmpty: true,
1045
- allowReserved: true
1046
- }).split("/").filter(Boolean).join("/");
1047
- }
1048
- function dedupeProviderPromise(promises, key, load) {
1049
- const promise = promises.get(key);
1050
- if (promise) return promise;
1051
- const nextPromise = load().finally(() => {
1052
- promises.delete(key);
1053
- });
1054
- promises.set(key, nextPromise);
1055
- return nextPromise;
1056
- }
1057
- async function waitForCachedGitHubResult(load, signal) {
1058
- signal?.throwIfAborted();
1059
- const result = load();
1060
- if (!signal) return await result;
1061
- return await new Promise((resolve, reject) => {
1062
- const abort = () => reject(signal.reason);
1063
- signal.addEventListener("abort", abort, { once: true });
1064
- result.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
1065
- });
1066
- }
1067
- function github(options) {
1068
- const configuredRef = options.ref;
1069
- const root = normalizeGitHubRoot(options.root || "");
1070
- const sparsePatterns = getGitSparsePatterns(root, options.include);
1071
- const authByContext = /* @__PURE__ */ new WeakMap();
1072
- const providerCache = normalizeGitHubCache(options);
1073
- const client = createGitHubClient(options.repo);
1074
- async function resolveAuth() {
1075
- if (options.auth === void 0) return githubEnvToken();
1076
- const token = typeof options.auth === "function" ? await options.auth() : options.auth;
1077
- return typeof token === "string" && token.length > 0 ? token : void 0;
1078
- }
1079
- async function contextAuth(ctx) {
1080
- let auth = authByContext.get(ctx);
1081
- if (!auth) {
1082
- auth = resolveAuth();
1083
- authByContext.set(ctx, auth);
1084
- }
1085
- return await auth;
1086
- }
1087
- function keyForRepoPath(path) {
1088
- let normalized;
1089
- try {
1090
- normalized = normalizeSafeSourcePath(path);
1091
- } catch {
1092
- return;
1093
- }
1094
- if (!root) return normalized;
1095
- if (!normalized.startsWith(`${root}/`)) return void 0;
1096
- const key = normalized.slice(root.length + 1);
1097
- if (!key || key.startsWith("/")) return void 0;
1098
- return normalizeSafeSourcePath(key);
1099
- }
1100
- function repoPathForKey(key) {
1101
- const normalized = normalizeSourcePath(key);
1102
- return root ? `${root}/${normalized}` : normalized;
1103
- }
1104
- function shouldInclude(key) {
1105
- if (options.include && !matchesAny(key, options.include)) return false;
1106
- if (options.ignore && matchesAny(key, options.ignore)) return false;
1107
- return true;
1108
- }
1109
- async function resolveRef(token) {
1110
- if (configuredRef) return configuredRef;
1111
- return (await resolveSourceRevision(token)).id;
1112
- }
1113
- async function resolveSourceRevision(token, signal) {
1114
- if (!configuredRef) try {
1115
- const ref = await client.defaultBranch(token, signal);
1116
- return {
1117
- id: await client.resolveCommit(ref, token, signal),
1118
- immutable: true,
1119
- ref
1120
- };
1121
- } catch (error) {
1122
- if (shouldResolveMainFallback(error)) return {
1123
- id: "main",
1124
- immutable: false,
1125
- ref: "main"
1126
- };
1127
- throw error;
1128
- }
1129
- try {
1130
- return {
1131
- id: await client.resolveCommit(configuredRef, token, signal),
1132
- immutable: true,
1133
- ref: configuredRef
1134
- };
1135
- } catch (error) {
1136
- if (shouldResolveMainFallback(error)) return {
1137
- id: configuredRef,
1138
- immutable: false,
1139
- ref: configuredRef
1140
- };
1141
- throw error;
1142
- }
1143
- }
1144
- function shouldResolveMainFallback(error) {
1145
- const status = githubErrorStatus(error);
1146
- return status === 403 || status === 429;
1147
- }
1148
- const resolvedRefs = /* @__PURE__ */ new Map();
1149
- const cachedResolveRef = providerCache ? defineCachedFunction(async (token) => await resolveRef(token), {
1150
- ...providerCache,
1151
- getKey: (token) => cacheKey("ref", token || ""),
1152
- name: "github-source-ref"
1153
- }) : (token) => dedupeProviderPromise(resolvedRefs, cacheKey("ref", token || ""), () => resolveRef(token));
1154
- async function getRef(token, signal) {
1155
- return await waitForCachedGitHubResult(() => cachedResolveRef(token), signal);
1156
- }
1157
- async function validateConfiguredRef(token) {
1158
- if (!configuredRef) return;
1159
- await client.resolveCommit(configuredRef, token);
1160
- }
1161
- async function loadArchiveFiles(token, resolvedRef) {
1162
- const ref = resolvedRef ?? await getRef(token);
1163
- return parseGitHubArchive(await client.archive(ref, token)).map((entry) => {
1164
- const key = keyForRepoPath(entry.path);
1165
- if (!key || !shouldInclude(key)) return void 0;
1166
- return {
1167
- content: entry.content,
1168
- key,
1169
- path: key,
1170
- ref,
1171
- sha: ref
1172
- };
1173
- }).filter((file) => Boolean(file));
1174
- }
1175
- async function loadFiles(token, resolvedRef) {
1176
- const ref = resolvedRef ?? await getRef(token);
1177
- if (sparsePatterns) try {
1178
- return await loadGitArchiveFiles({
1179
- credentials: forgeGitCredentials({
1180
- forge: "github",
1181
- repository: options.repo,
1182
- token
1183
- }),
1184
- keyForRepoPath,
1185
- ref,
1186
- shouldInclude,
1187
- signal: void 0,
1188
- sparsePatterns
1189
- });
1190
- } catch {}
1191
- return await loadArchiveFiles(token, ref);
1192
- }
1193
- const loadedFiles = /* @__PURE__ */ new Map();
1194
- const cachedLoadFiles = providerCache ? defineCachedFunction(async (resolvedRef, token) => await loadFiles(token, resolvedRef), {
1195
- ...providerCache,
1196
- getKey: (resolvedRef, token) => cacheKey("archive", token, "", resolvedRef),
1197
- name: "github-source-archive"
1198
- }) : (resolvedRef, token) => dedupeProviderPromise(loadedFiles, cacheKey("archive", token, "", resolvedRef), () => loadFiles(token, resolvedRef));
1199
- function getFiles(token, signal, resolvedRef) {
1200
- return waitForCachedGitHubResult(() => cachedLoadFiles(resolvedRef, token), signal);
1201
- }
1202
- async function loadFileMetadata(key, token, resolvedRef) {
1203
- let normalizedKey;
1204
- try {
1205
- normalizedKey = normalizeSafeSourcePath(key);
1206
- } catch {
1207
- return;
1208
- }
1209
- if (!normalizedKey || !shouldInclude(normalizedKey)) return;
1210
- const ref = resolvedRef ?? await getRef(token);
1211
- const repoPath = repoPathForKey(normalizedKey);
1212
- let file;
1213
- try {
1214
- file = await client.metadata(repoPath, ref, token);
1215
- } catch (error) {
1216
- if (isGitHubAccessError(error)) {
1217
- await validateConfiguredRef(token);
1218
- return;
1219
- }
1220
- if (shouldResolveMainFallback(error)) return (await getFiles(token, void 0, ref)).find((file) => file.key === normalizedKey);
1221
- throw error;
1222
- }
1223
- if (!file) return;
1224
- return {
1225
- key: normalizedKey,
1226
- path: normalizedKey,
1227
- ref,
1228
- sha: file.sha
1229
- };
1230
- }
1231
- const loadedFileMetadata = /* @__PURE__ */ new Map();
1232
- const cachedLoadFileMetadata = providerCache ? defineCachedFunction(async (key, resolvedRef, token) => await loadFileMetadata(key, token, resolvedRef), {
1233
- ...providerCache,
1234
- getKey: (key, resolvedRef, token) => cacheKey("metadata", token, key, resolvedRef),
1235
- name: "github-source-metadata"
1236
- }) : (key, resolvedRef, token) => dedupeProviderPromise(loadedFileMetadata, cacheKey("metadata", token, key, resolvedRef), () => loadFileMetadata(key, token, resolvedRef));
1237
- function isGitHubAccessError(error) {
1238
- return githubErrorStatus(error) === 404;
1239
- }
1240
- async function loadFile(key, token, signal, resolvedRef) {
1241
- let normalizedKey;
1242
- try {
1243
- normalizedKey = normalizeSafeSourcePath(key);
1244
- } catch {
1245
- throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
1246
- }
1247
- if (!normalizedKey || !shouldInclude(normalizedKey)) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
1248
- const ref = resolvedRef ?? await getRef(token, signal);
1249
- const repoPath = repoPathForKey(normalizedKey);
1250
- const file = await client.file(repoPath, ref, token, signal);
1251
- return {
1252
- content: file.content,
1253
- key: normalizedKey,
1254
- path: normalizedKey,
1255
- ref,
1256
- sha: file.sha || ref
1257
- };
1258
- }
1259
- async function getFile(key, ctx, token) {
1260
- if (ctx?.abortSignal) return await loadFile(key, token, ctx.abortSignal, ctx.revision?.id);
1261
- const file = (await getFiles(token, void 0, ctx?.revision?.id)).find((file) => file.key === key);
1262
- if (!file) throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) could not find ${JSON.stringify(key)}.`);
1263
- return file;
1264
- }
1265
- function fetchContent(key, file) {
1266
- if (file.content) return file.content;
1267
- throw sourceError(`[vitehub] github(${JSON.stringify(options.repo)}) did not include archive content for ${JSON.stringify(key)}.`);
1268
- }
1269
- function cacheKey(kind, token, key = "", resolvedRef) {
1270
- return createGitHubCacheKey({
1271
- authScope: githubAuthenticationScope(token),
1272
- ignore: options.ignore,
1273
- include: options.include,
1274
- key,
1275
- kind,
1276
- ref: resolvedRef || configuredRef || "default",
1277
- repo: options.repo,
1278
- root
1279
- });
1280
- }
1281
- return {
1282
- cache: options.cache,
1283
- fingerprint: {
1284
- ignore: options.ignore,
1285
- include: options.include,
1286
- ref: configuredRef || "default",
1287
- repo: options.repo,
1288
- root
1289
- },
1290
- name: "github",
1291
- async resolveRevision(ctx) {
1292
- return await resolveSourceRevision(await contextAuth(ctx), ctx.abortSignal);
1293
- },
1294
- async getKeys(ctx) {
1295
- return (await getFiles(await contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => file.key);
1296
- },
1297
- async getItems(ctx) {
1298
- return (await getFiles(await contextAuth(ctx), ctx.abortSignal, ctx.revision?.id)).map((file) => ({
1299
- key: file.key,
1300
- path: file.path,
1301
- content: fetchContent(file.key, file),
1302
- metadata: {
1303
- ref: file.ref,
1304
- sha: file.sha
1305
- }
1306
- }));
1307
- },
1308
- async getMeta(key, ctx) {
1309
- const token = await contextAuth(ctx);
1310
- const file = await waitForCachedGitHubResult(() => cachedLoadFileMetadata(key, ctx.revision?.id, token), ctx?.abortSignal);
1311
- if (!file) return;
1312
- return {
1313
- ref: file.ref,
1314
- sha: file.sha
1315
- };
1316
- },
1317
- async getItem(key, ctx) {
1318
- const file = await getFile(key, ctx, await contextAuth(ctx));
1319
- return {
1320
- key: file.key,
1321
- path: file.path,
1322
- content: fetchContent(key, file),
1323
- metadata: {
1324
- ref: file.ref,
1325
- sha: file.sha
1326
- }
1327
- };
1328
- }
1329
- };
1330
- }
1331
- //#endregion
1332
- export { github };