@vite-hub/source 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +302 -31
  3. package/dist/auth-B-tX_rp0.js +1426 -0
  4. package/dist/client-BwstxtdY.js +8280 -0
  5. package/dist/client.d.ts +49 -0
  6. package/dist/client.js +179 -0
  7. package/dist/collection-B_4w_J8h.d.ts +257 -0
  8. package/dist/collection-cursor-WzV1Jd6v.js +124 -0
  9. package/dist/collection-route-BplWPxHR.js +10 -0
  10. package/dist/drizzle.d.ts +41 -0
  11. package/dist/drizzle.js +89 -0
  12. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  13. package/dist/file-BX0FSvgE.js +60 -0
  14. package/dist/file-DadN9dbN.d.ts +19 -0
  15. package/dist/file.d.ts +2 -0
  16. package/dist/file.js +2 -0
  17. package/dist/files.d.ts +15 -0
  18. package/dist/files.js +38 -0
  19. package/dist/github.d.ts +20 -0
  20. package/dist/github.js +1332 -0
  21. package/dist/glob-BmFqTvJY.js +993 -0
  22. package/dist/glob.d.ts +23 -0
  23. package/dist/glob.js +2 -0
  24. package/dist/index.d.ts +165 -172
  25. package/dist/index.js +600 -1113
  26. package/dist/markdown.d.ts +5 -0
  27. package/dist/markdown.js +10 -0
  28. package/dist/mcp.d.ts +151 -0
  29. package/dist/mcp.js +497 -0
  30. package/dist/mrmime-40h5OOIp.js +448 -0
  31. package/dist/path-BS8rYm0n.js +1956 -0
  32. package/dist/path-DOBpV8ol.js +32 -0
  33. package/dist/server.d.ts +265 -0
  34. package/dist/server.js +149 -0
  35. package/dist/sse-D9gqqNPj.js +448 -0
  36. package/dist/streamableHttp-BL-E7pl5.js +509 -0
  37. package/dist/types-BigOktIj.d.ts +93 -0
  38. package/dist/types-CoWcW8oz.js +7590 -0
  39. package/dist/vite.d.ts +162 -0
  40. package/dist/vite.js +2284 -0
  41. package/package.json +102 -17
  42. package/tsconfig.vite.json +6 -0
  43. package/types/source/fallback.d.ts +1 -0
  44. package/types/source/index.d.ts +1 -0
@@ -0,0 +1,993 @@
1
+ import { a as __toESM, r as require_picomatch, t as createPathMatcher } from "./path-BS8rYm0n.js";
2
+ import { i as sourceError, n as normalizeSafeSourcePath, r as normalizeSourcePath } from "./path-DOBpV8ol.js";
3
+ import * as nativeFs from "fs";
4
+ import { readdir, readdirSync, realpath, realpathSync, stat, statSync } from "fs";
5
+ import { basename, dirname, isAbsolute, normalize, posix, relative, resolve, sep } from "path";
6
+ import { fileURLToPath } from "url";
7
+ //#region ../../node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.7/node_modules/fdir/dist/index.mjs
8
+ function cleanPath(path) {
9
+ let normalized = normalize(path);
10
+ if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1);
11
+ return normalized;
12
+ }
13
+ const SLASHES_REGEX = /[\\/]/g;
14
+ function convertSlashes(path, separator) {
15
+ return path.replace(SLASHES_REGEX, separator);
16
+ }
17
+ const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
18
+ function isRootDirectory(path) {
19
+ return path === "/" || WINDOWS_ROOT_DIR_REGEX.test(path);
20
+ }
21
+ function normalizePath(path, options) {
22
+ const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
23
+ const pathNeedsCleaning = process.platform === "win32" && path.includes("/") || path.startsWith(".");
24
+ if (resolvePaths) path = resolve(path);
25
+ if (normalizePath$1 || pathNeedsCleaning) path = cleanPath(path);
26
+ if (path === ".") return "";
27
+ return convertSlashes(path[path.length - 1] !== pathSeparator ? path + pathSeparator : path, pathSeparator);
28
+ }
29
+ function joinPathWithBasePath(filename, directoryPath) {
30
+ return directoryPath + filename;
31
+ }
32
+ function joinPathWithRelativePath(root, options) {
33
+ return function(filename, directoryPath) {
34
+ if (directoryPath.startsWith(root)) return directoryPath.slice(root.length) + filename;
35
+ else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
36
+ };
37
+ }
38
+ function joinPath(filename) {
39
+ return filename;
40
+ }
41
+ function joinDirectoryPath(filename, directoryPath, separator) {
42
+ return directoryPath + filename + separator;
43
+ }
44
+ function build$7(root, options) {
45
+ const { relativePaths, includeBasePath } = options;
46
+ return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
47
+ }
48
+ function pushDirectoryWithRelativePath(root) {
49
+ return function(directoryPath, paths) {
50
+ paths.push(directoryPath.substring(root.length) || ".");
51
+ };
52
+ }
53
+ function pushDirectoryFilterWithRelativePath(root) {
54
+ return function(directoryPath, paths, filters) {
55
+ const relativePath = directoryPath.substring(root.length) || ".";
56
+ if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
57
+ };
58
+ }
59
+ const pushDirectory = (directoryPath, paths) => {
60
+ paths.push(directoryPath || ".");
61
+ };
62
+ const pushDirectoryFilter = (directoryPath, paths, filters) => {
63
+ const path = directoryPath || ".";
64
+ if (filters.every((filter) => filter(path, true))) paths.push(path);
65
+ };
66
+ const empty$2 = () => {};
67
+ function build$6(root, options) {
68
+ const { includeDirs, filters, relativePaths } = options;
69
+ if (!includeDirs) return empty$2;
70
+ if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
71
+ return filters && filters.length ? pushDirectoryFilter : pushDirectory;
72
+ }
73
+ const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
74
+ if (filters.every((filter) => filter(filename, false))) counts.files++;
75
+ };
76
+ const pushFileFilter = (filename, paths, _counts, filters) => {
77
+ if (filters.every((filter) => filter(filename, false))) paths.push(filename);
78
+ };
79
+ const pushFileCount = (_filename, _paths, counts, _filters) => {
80
+ counts.files++;
81
+ };
82
+ const pushFile = (filename, paths) => {
83
+ paths.push(filename);
84
+ };
85
+ const empty$1 = () => {};
86
+ function build$5(options) {
87
+ const { excludeFiles, filters, onlyCounts } = options;
88
+ if (excludeFiles) return empty$1;
89
+ if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
90
+ else if (onlyCounts) return pushFileCount;
91
+ else return pushFile;
92
+ }
93
+ const getArray = (paths) => {
94
+ return paths;
95
+ };
96
+ const getArrayGroup = () => {
97
+ return [""].slice(0, 0);
98
+ };
99
+ function build$4(options) {
100
+ return options.group ? getArrayGroup : getArray;
101
+ }
102
+ const groupFiles = (groups, directory, files) => {
103
+ groups.push({
104
+ directory,
105
+ files,
106
+ dir: directory
107
+ });
108
+ };
109
+ const empty = () => {};
110
+ function build$3(options) {
111
+ return options.group ? groupFiles : empty;
112
+ }
113
+ const resolveSymlinksAsync = function(path, state, callback$1) {
114
+ const { queue, fs, options: { suppressErrors } } = state;
115
+ queue.enqueue();
116
+ fs.realpath(path, (error, resolvedPath) => {
117
+ if (error) return queue.dequeue(suppressErrors ? null : error, state);
118
+ fs.stat(resolvedPath, (error$1, stat) => {
119
+ if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
120
+ if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return queue.dequeue(null, state);
121
+ callback$1(stat, resolvedPath);
122
+ queue.dequeue(null, state);
123
+ });
124
+ });
125
+ };
126
+ const resolveSymlinks = function(path, state, callback$1) {
127
+ const { queue, fs, options: { suppressErrors } } = state;
128
+ queue.enqueue();
129
+ try {
130
+ const resolvedPath = fs.realpathSync(path);
131
+ const stat = fs.statSync(resolvedPath);
132
+ if (stat.isDirectory() && isRecursive(path, resolvedPath, state)) return;
133
+ callback$1(stat, resolvedPath);
134
+ } catch (e) {
135
+ if (!suppressErrors) throw e;
136
+ }
137
+ };
138
+ function build$2(options, isSynchronous) {
139
+ if (!options.resolveSymlinks || options.excludeSymlinks) return null;
140
+ return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
141
+ }
142
+ function isRecursive(path, resolved, state) {
143
+ if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
144
+ let parent = dirname(path);
145
+ let depth = 1;
146
+ while (parent !== state.root && depth < 2) {
147
+ const resolvedPath = state.symlinks.get(parent);
148
+ if (!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath))) depth++;
149
+ else parent = dirname(parent);
150
+ }
151
+ state.symlinks.set(path, resolved);
152
+ return depth > 1;
153
+ }
154
+ function isRecursiveUsingRealPaths(resolved, state) {
155
+ return state.visited.includes(resolved + state.options.pathSeparator);
156
+ }
157
+ const onlyCountsSync = (state) => {
158
+ return state.counts;
159
+ };
160
+ const groupsSync = (state) => {
161
+ return state.groups;
162
+ };
163
+ const defaultSync = (state) => {
164
+ return state.paths;
165
+ };
166
+ const limitFilesSync = (state) => {
167
+ return state.paths.slice(0, state.options.maxFiles);
168
+ };
169
+ const onlyCountsAsync = (state, error, callback$1) => {
170
+ report(error, callback$1, state.counts, state.options.suppressErrors);
171
+ return null;
172
+ };
173
+ const defaultAsync = (state, error, callback$1) => {
174
+ report(error, callback$1, state.paths, state.options.suppressErrors);
175
+ return null;
176
+ };
177
+ const limitFilesAsync = (state, error, callback$1) => {
178
+ report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
179
+ return null;
180
+ };
181
+ const groupsAsync = (state, error, callback$1) => {
182
+ report(error, callback$1, state.groups, state.options.suppressErrors);
183
+ return null;
184
+ };
185
+ function report(error, callback$1, output, suppressErrors) {
186
+ if (error && !suppressErrors) callback$1(error, output);
187
+ else callback$1(null, output);
188
+ }
189
+ function build$1(options, isSynchronous) {
190
+ const { onlyCounts, group, maxFiles } = options;
191
+ if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
192
+ else if (group) return isSynchronous ? groupsSync : groupsAsync;
193
+ else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
194
+ else return isSynchronous ? defaultSync : defaultAsync;
195
+ }
196
+ const readdirOpts = { withFileTypes: true };
197
+ const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
198
+ state.queue.enqueue();
199
+ if (currentDepth < 0) return state.queue.dequeue(null, state);
200
+ const { fs } = state;
201
+ state.visited.push(crawlPath);
202
+ state.counts.directories++;
203
+ fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
204
+ callback$1(entries, directoryPath, currentDepth);
205
+ state.queue.dequeue(state.options.suppressErrors ? null : error, state);
206
+ });
207
+ };
208
+ const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
209
+ const { fs } = state;
210
+ if (currentDepth < 0) return;
211
+ state.visited.push(crawlPath);
212
+ state.counts.directories++;
213
+ let entries = [];
214
+ try {
215
+ entries = fs.readdirSync(crawlPath || ".", readdirOpts);
216
+ } catch (e) {
217
+ if (!state.options.suppressErrors) throw e;
218
+ }
219
+ callback$1(entries, directoryPath, currentDepth);
220
+ };
221
+ function build(isSynchronous) {
222
+ return isSynchronous ? walkSync : walkAsync;
223
+ }
224
+ /**
225
+ * This is a custom stateless queue to track concurrent async fs calls.
226
+ * It increments a counter whenever a call is queued and decrements it
227
+ * as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
228
+ */
229
+ var Queue = class {
230
+ count = 0;
231
+ constructor(onQueueEmpty) {
232
+ this.onQueueEmpty = onQueueEmpty;
233
+ }
234
+ enqueue() {
235
+ this.count++;
236
+ return this.count;
237
+ }
238
+ dequeue(error, output) {
239
+ if (this.onQueueEmpty && (--this.count <= 0 || error)) {
240
+ this.onQueueEmpty(error, output);
241
+ if (error) {
242
+ output.controller.abort();
243
+ this.onQueueEmpty = void 0;
244
+ }
245
+ }
246
+ }
247
+ };
248
+ var Counter = class {
249
+ _files = 0;
250
+ _directories = 0;
251
+ set files(num) {
252
+ this._files = num;
253
+ }
254
+ get files() {
255
+ return this._files;
256
+ }
257
+ set directories(num) {
258
+ this._directories = num;
259
+ }
260
+ get directories() {
261
+ return this._directories;
262
+ }
263
+ /**
264
+ * @deprecated use `directories` instead
265
+ */
266
+ /* c8 ignore next 3 */
267
+ get dirs() {
268
+ return this._directories;
269
+ }
270
+ };
271
+ /**
272
+ * AbortController is not supported on Node 14 so we use this until we can drop
273
+ * support for Node 14.
274
+ */
275
+ var Aborter = class {
276
+ aborted = false;
277
+ abort() {
278
+ this.aborted = true;
279
+ }
280
+ };
281
+ var Walker = class {
282
+ root;
283
+ isSynchronous;
284
+ state;
285
+ joinPath;
286
+ pushDirectory;
287
+ pushFile;
288
+ getArray;
289
+ groupFiles;
290
+ resolveSymlink;
291
+ walkDirectory;
292
+ callbackInvoker;
293
+ constructor(root, options, callback$1) {
294
+ this.isSynchronous = !callback$1;
295
+ this.callbackInvoker = build$1(options, this.isSynchronous);
296
+ this.root = normalizePath(root, options);
297
+ this.state = {
298
+ root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
299
+ paths: [""].slice(0, 0),
300
+ groups: [],
301
+ counts: new Counter(),
302
+ options,
303
+ queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
304
+ symlinks: /* @__PURE__ */ new Map(),
305
+ visited: [""].slice(0, 0),
306
+ controller: new Aborter(),
307
+ fs: options.fs || nativeFs
308
+ };
309
+ this.joinPath = build$7(this.root, options);
310
+ this.pushDirectory = build$6(this.root, options);
311
+ this.pushFile = build$5(options);
312
+ this.getArray = build$4(options);
313
+ this.groupFiles = build$3(options);
314
+ this.resolveSymlink = build$2(options, this.isSynchronous);
315
+ this.walkDirectory = build(this.isSynchronous);
316
+ }
317
+ start() {
318
+ this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
319
+ this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
320
+ return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
321
+ }
322
+ walk = (entries, directoryPath, depth) => {
323
+ const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
324
+ if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
325
+ const files = this.getArray(this.state.paths);
326
+ for (let i = 0; i < entries.length; ++i) {
327
+ const entry = entries[i];
328
+ if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
329
+ const filename = this.joinPath(entry.name, directoryPath);
330
+ this.pushFile(filename, files, this.state.counts, filters);
331
+ } else if (entry.isDirectory()) {
332
+ let path = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
333
+ if (exclude && exclude(entry.name, path)) continue;
334
+ this.pushDirectory(path, paths, filters);
335
+ this.walkDirectory(this.state, path, path, depth - 1, this.walk);
336
+ } else if (this.resolveSymlink && entry.isSymbolicLink()) {
337
+ let path = joinPathWithBasePath(entry.name, directoryPath);
338
+ this.resolveSymlink(path, this.state, (stat, resolvedPath) => {
339
+ if (stat.isDirectory()) {
340
+ resolvedPath = normalizePath(resolvedPath, this.state.options);
341
+ if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path + pathSeparator)) return;
342
+ this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path + pathSeparator, depth - 1, this.walk);
343
+ } else {
344
+ resolvedPath = useRealPaths ? resolvedPath : path;
345
+ const filename = basename(resolvedPath);
346
+ const directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options);
347
+ resolvedPath = this.joinPath(filename, directoryPath$1);
348
+ this.pushFile(resolvedPath, files, this.state.counts, filters);
349
+ }
350
+ });
351
+ }
352
+ }
353
+ this.groupFiles(this.state.groups, directoryPath, files);
354
+ };
355
+ };
356
+ function promise(root, options) {
357
+ return new Promise((resolve$1, reject) => {
358
+ callback(root, options, (err, output) => {
359
+ if (err) return reject(err);
360
+ resolve$1(output);
361
+ });
362
+ });
363
+ }
364
+ function callback(root, options, callback$1) {
365
+ new Walker(root, options, callback$1).start();
366
+ }
367
+ function sync(root, options) {
368
+ return new Walker(root, options).start();
369
+ }
370
+ var APIBuilder = class {
371
+ constructor(root, options) {
372
+ this.root = root;
373
+ this.options = options;
374
+ }
375
+ withPromise() {
376
+ return promise(this.root, this.options);
377
+ }
378
+ withCallback(cb) {
379
+ callback(this.root, this.options, cb);
380
+ }
381
+ sync() {
382
+ return sync(this.root, this.options);
383
+ }
384
+ };
385
+ let pm = null;
386
+ var Builder = class {
387
+ globCache = {};
388
+ options = {
389
+ maxDepth: Infinity,
390
+ suppressErrors: true,
391
+ pathSeparator: sep,
392
+ filters: []
393
+ };
394
+ globFunction;
395
+ constructor(options) {
396
+ this.options = {
397
+ ...this.options,
398
+ ...options
399
+ };
400
+ this.globFunction = this.options.globFunction;
401
+ }
402
+ group() {
403
+ this.options.group = true;
404
+ return this;
405
+ }
406
+ withPathSeparator(separator) {
407
+ this.options.pathSeparator = separator;
408
+ return this;
409
+ }
410
+ withBasePath() {
411
+ this.options.includeBasePath = true;
412
+ return this;
413
+ }
414
+ withRelativePaths() {
415
+ this.options.relativePaths = true;
416
+ return this;
417
+ }
418
+ withDirs() {
419
+ this.options.includeDirs = true;
420
+ return this;
421
+ }
422
+ withMaxDepth(depth) {
423
+ this.options.maxDepth = depth;
424
+ return this;
425
+ }
426
+ withMaxFiles(limit) {
427
+ this.options.maxFiles = limit;
428
+ return this;
429
+ }
430
+ withFullPaths() {
431
+ this.options.resolvePaths = true;
432
+ this.options.includeBasePath = true;
433
+ return this;
434
+ }
435
+ withErrors() {
436
+ this.options.suppressErrors = false;
437
+ return this;
438
+ }
439
+ withSymlinks({ resolvePaths = true } = {}) {
440
+ this.options.resolveSymlinks = true;
441
+ this.options.useRealPaths = resolvePaths;
442
+ return this.withFullPaths();
443
+ }
444
+ withAbortSignal(signal) {
445
+ this.options.signal = signal;
446
+ return this;
447
+ }
448
+ normalize() {
449
+ this.options.normalizePath = true;
450
+ return this;
451
+ }
452
+ filter(predicate) {
453
+ this.options.filters.push(predicate);
454
+ return this;
455
+ }
456
+ onlyDirs() {
457
+ this.options.excludeFiles = true;
458
+ this.options.includeDirs = true;
459
+ return this;
460
+ }
461
+ exclude(predicate) {
462
+ this.options.exclude = predicate;
463
+ return this;
464
+ }
465
+ onlyCounts() {
466
+ this.options.onlyCounts = true;
467
+ return this;
468
+ }
469
+ crawl(root) {
470
+ return new APIBuilder(root || ".", this.options);
471
+ }
472
+ withGlobFunction(fn) {
473
+ this.globFunction = fn;
474
+ return this;
475
+ }
476
+ /**
477
+ * @deprecated Pass options using the constructor instead:
478
+ * ```ts
479
+ * new fdir(options).crawl("/path/to/root");
480
+ * ```
481
+ * This method will be removed in v7.0
482
+ */
483
+ /* c8 ignore next 4 */
484
+ crawlWithOptions(root, options) {
485
+ this.options = {
486
+ ...this.options,
487
+ ...options
488
+ };
489
+ return new APIBuilder(root || ".", this.options);
490
+ }
491
+ glob(...patterns) {
492
+ if (this.globFunction) return this.globWithOptions(patterns);
493
+ return this.globWithOptions(patterns, ...[{ dot: true }]);
494
+ }
495
+ globWithOptions(patterns, ...options) {
496
+ const globFn = this.globFunction || pm;
497
+ /* c8 ignore next 5 */
498
+ if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
499
+ var isMatch = this.globCache[patterns.join("\0")];
500
+ if (!isMatch) {
501
+ isMatch = globFn(patterns, ...options);
502
+ this.globCache[patterns.join("\0")] = isMatch;
503
+ }
504
+ this.options.filters.push((path) => isMatch(path));
505
+ return this;
506
+ }
507
+ };
508
+ //#endregion
509
+ //#region ../../node_modules/.pnpm/tinyglobby@0.2.17/node_modules/tinyglobby/dist/index.mjs
510
+ var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
511
+ const isReadonlyArray = Array.isArray;
512
+ const BACKSLASHES = /\\/g;
513
+ const DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/;
514
+ const isWin = process.platform === "win32";
515
+ const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
516
+ function getPartialMatcher(patterns, options = {}) {
517
+ const patternsCount = patterns.length;
518
+ const patternsParts = Array(patternsCount);
519
+ const matchers = Array(patternsCount);
520
+ let i, j;
521
+ for (i = 0; i < patternsCount; i++) {
522
+ const parts = splitPattern(patterns[i]);
523
+ patternsParts[i] = parts;
524
+ const partsCount = parts.length;
525
+ const partMatchers = Array(partsCount);
526
+ for (j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
527
+ matchers[i] = partMatchers;
528
+ }
529
+ return (input) => {
530
+ const inputParts = input.split("/");
531
+ if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
532
+ for (i = 0; i < patternsCount; i++) {
533
+ const patternParts = patternsParts[i];
534
+ const matcher = matchers[i];
535
+ const inputPatternCount = inputParts.length;
536
+ const minParts = Math.min(inputPatternCount, patternParts.length);
537
+ j = 0;
538
+ while (j < minParts) {
539
+ const part = patternParts[j];
540
+ if (part.includes("/")) return true;
541
+ if (!matcher[j](inputParts[j])) break;
542
+ if (!options.noglobstar && part === "**") return true;
543
+ j++;
544
+ }
545
+ if (j === inputPatternCount) return true;
546
+ }
547
+ return false;
548
+ };
549
+ }
550
+ /* node:coverage ignore next 2 */
551
+ const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
552
+ const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
553
+ function buildFormat(cwd, root, absolute) {
554
+ if (cwd === root || root.startsWith(`${cwd}/`)) {
555
+ if (absolute) {
556
+ const start = cwd.length + +!isRoot(cwd);
557
+ return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
558
+ }
559
+ const prefix = root.slice(cwd.length + 1);
560
+ if (prefix) return (p, isDir) => {
561
+ if (p === ".") return prefix;
562
+ const result = `${prefix}/${p}`;
563
+ return isDir ? result.slice(0, -1) : result;
564
+ };
565
+ return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
566
+ }
567
+ if (absolute) return (p) => posix.relative(cwd, p) || ".";
568
+ return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
569
+ }
570
+ function buildRelative(cwd, root) {
571
+ if (root.startsWith(`${cwd}/`)) {
572
+ const prefix = root.slice(cwd.length + 1);
573
+ return (p) => `${prefix}/${p}`;
574
+ }
575
+ return (p) => {
576
+ const result = posix.relative(cwd, `${root}/${p}`);
577
+ return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
578
+ };
579
+ }
580
+ function ensureNonDriveRelativePath(path) {
581
+ return path.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
582
+ }
583
+ const splitPatternOptions = { parts: true };
584
+ function splitPattern(path) {
585
+ var _result$parts;
586
+ const result = import_picomatch.default.scan(path, splitPatternOptions);
587
+ return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path];
588
+ }
589
+ const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
590
+ const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
591
+ const escapePosixPath = (path) => path.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
592
+ const escapeWin32Path = (path) => path.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
593
+ /**
594
+ * Escapes a path's special characters depending on the platform.
595
+ * @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
596
+ */
597
+ /* node:coverage ignore next */
598
+ const escapePath = isWin ? escapeWin32Path : escapePosixPath;
599
+ /**
600
+ * Checks if a pattern has dynamic parts.
601
+ *
602
+ * Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
603
+ *
604
+ * - Doesn't necessarily return `false` on patterns that include `\`.
605
+ * - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
606
+ * - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
607
+ * - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
608
+ *
609
+ * @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
610
+ */
611
+ function isDynamicPattern(pattern, options) {
612
+ if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
613
+ const scan = import_picomatch.default.scan(pattern);
614
+ return scan.isGlob || scan.negated;
615
+ }
616
+ function log(...tasks) {
617
+ console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
618
+ }
619
+ function ensureStringArray(value) {
620
+ return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : [];
621
+ }
622
+ const PARENT_DIRECTORY = /^(\/?\.\.)+/;
623
+ const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
624
+ function normalizePattern(pattern, opts, props, isIgnore) {
625
+ var _PARENT_DIRECTORY$exe;
626
+ const cwd = opts.cwd;
627
+ let result = pattern;
628
+ if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1);
629
+ if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**";
630
+ const escapedCwd = escapePath(cwd);
631
+ result = isAbsolute(result.replace(ESCAPING_BACKSLASHES, "")) ? posix.relative(escapedCwd, result) : posix.normalize(result);
632
+ const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0];
633
+ const parts = splitPattern(result);
634
+ if (parentDir) {
635
+ const n = (parentDir.length + 1) / 3;
636
+ let i = 0;
637
+ const cwdParts = escapedCwd.split("/");
638
+ while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
639
+ result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
640
+ i++;
641
+ }
642
+ const potentialRoot = posix.join(cwd, parentDir.slice(i * 3));
643
+ if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) {
644
+ props.root = ensureNonDriveRelativePath(potentialRoot);
645
+ props.depthOffset = -n + i;
646
+ }
647
+ }
648
+ if (!isIgnore && props.depthOffset >= 0) {
649
+ var _props$commonPath;
650
+ (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
651
+ const newCommonPath = [];
652
+ const length = Math.min(props.commonPath.length, parts.length);
653
+ for (let i = 0; i < length; i++) {
654
+ const part = parts[i];
655
+ if (part === "**" && !parts[i + 1]) {
656
+ newCommonPath.pop();
657
+ break;
658
+ }
659
+ if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break;
660
+ newCommonPath.push(part);
661
+ }
662
+ props.depthOffset = newCommonPath.length;
663
+ props.commonPath = newCommonPath;
664
+ props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd);
665
+ }
666
+ return result;
667
+ }
668
+ function processPatterns(options, patterns, props) {
669
+ const matchPatterns = [];
670
+ const ignorePatterns = [];
671
+ for (const pattern of options.ignore) {
672
+ if (!pattern) continue;
673
+ if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true));
674
+ }
675
+ for (const pattern of patterns) {
676
+ if (!pattern) continue;
677
+ if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false));
678
+ else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true));
679
+ }
680
+ return {
681
+ match: matchPatterns,
682
+ ignore: ignorePatterns
683
+ };
684
+ }
685
+ function buildCrawler(options, patterns) {
686
+ const cwd = options.cwd;
687
+ const props = {
688
+ root: cwd,
689
+ depthOffset: 0
690
+ };
691
+ const processed = processPatterns(options, patterns, props);
692
+ if (options.debug) log("internal processing patterns:", processed);
693
+ const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options;
694
+ const root = props.root.replace(BACKSLASHES, "");
695
+ const matchOptions = {
696
+ dot,
697
+ nobrace: options.braceExpansion === false,
698
+ nocase: !caseSensitiveMatch,
699
+ noextglob: options.extglob === false,
700
+ noglobstar: options.globstar === false,
701
+ posix: true
702
+ };
703
+ const matcher = (0, import_picomatch.default)(processed.match, matchOptions);
704
+ const ignore = (0, import_picomatch.default)(processed.ignore, matchOptions);
705
+ const partialMatcher = getPartialMatcher(processed.match, matchOptions);
706
+ const format = buildFormat(cwd, root, absolute);
707
+ const excludeFormatter = absolute ? format : buildFormat(cwd, root, true);
708
+ const excludePredicate = (_, p) => {
709
+ const relativePath = excludeFormatter(p, true);
710
+ return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
711
+ };
712
+ let maxDepth;
713
+ if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset);
714
+ const crawler = new Builder({
715
+ filters: [debug ? (p, isDirectory) => {
716
+ const path = format(p, isDirectory);
717
+ const matches = matcher(path) && !ignore(path);
718
+ if (matches) log(`matched ${path}`);
719
+ return matches;
720
+ } : (p, isDirectory) => {
721
+ const path = format(p, isDirectory);
722
+ return matcher(path) && !ignore(path);
723
+ }],
724
+ exclude: debug ? (_, p) => {
725
+ const skipped = excludePredicate(_, p);
726
+ log(`${skipped ? "skipped" : "crawling"} ${p}`);
727
+ return skipped;
728
+ } : excludePredicate,
729
+ fs: options.fs,
730
+ pathSeparator: "/",
731
+ relativePaths: !absolute,
732
+ resolvePaths: absolute,
733
+ includeBasePath: absolute,
734
+ resolveSymlinks: followSymbolicLinks,
735
+ excludeSymlinks: !followSymbolicLinks,
736
+ excludeFiles: onlyDirectories,
737
+ includeDirs: onlyDirectories || !options.onlyFiles,
738
+ maxDepth,
739
+ signal: options.signal
740
+ }).crawl(root);
741
+ if (options.debug) log("internal properties:", {
742
+ ...props,
743
+ root
744
+ });
745
+ return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)];
746
+ }
747
+ function formatPaths(paths, mapper) {
748
+ if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]);
749
+ return paths;
750
+ }
751
+ const defaultOptions = {
752
+ caseSensitiveMatch: true,
753
+ debug: !!process.env.TINYGLOBBY_DEBUG,
754
+ expandDirectories: true,
755
+ followSymbolicLinks: true,
756
+ onlyFiles: true
757
+ };
758
+ function getOptions(options) {
759
+ const opts = Object.assign({}, options);
760
+ for (const key in defaultOptions) if (opts[key] === void 0) Object.assign(opts, { [key]: defaultOptions[key] });
761
+ opts.cwd = (opts.cwd instanceof URL ? fileURLToPath(opts.cwd) : resolve(opts.cwd || process.cwd())).replace(BACKSLASHES, "/");
762
+ opts.ignore = ensureStringArray(opts.ignore);
763
+ opts.fs && (opts.fs = {
764
+ readdir: opts.fs.readdir || readdir,
765
+ readdirSync: opts.fs.readdirSync || readdirSync,
766
+ realpath: opts.fs.realpath || realpath,
767
+ realpathSync: opts.fs.realpathSync || realpathSync,
768
+ stat: opts.fs.stat || stat,
769
+ statSync: opts.fs.statSync || statSync
770
+ });
771
+ if (opts.debug) log("globbing with options:", opts);
772
+ return opts;
773
+ }
774
+ function getCrawler(globInput, inputOptions = {}) {
775
+ var _ref;
776
+ if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
777
+ const isModern = isReadonlyArray(globInput) || typeof globInput === "string";
778
+ const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*");
779
+ const options = getOptions(isModern ? inputOptions : globInput);
780
+ return patterns.length > 0 ? buildCrawler(options, patterns) : [];
781
+ }
782
+ async function glob$1(globInput, options) {
783
+ const [crawler, relative] = getCrawler(globInput, options);
784
+ return crawler ? formatPaths(await crawler.withPromise(), relative) : [];
785
+ }
786
+ //#endregion
787
+ //#region src/sources/glob.ts
788
+ /**
789
+ * The options a pattern stands for: the folders before its first wildcard are `cwd`, so keys are the paths below
790
+ * them (`content/docs/**\/*.md` keys `guide/setup.md`). A pattern without a wildcard names a folder: every file in it.
791
+ */
792
+ function resolveGlobInput(input) {
793
+ if (typeof input !== "string") return input;
794
+ const parts = input.replaceAll("\\", "/").replace(/^\.\//, "").split("/").filter(Boolean);
795
+ const wild = parts.findIndex((part) => /[*?[\]{}()!]/.test(part));
796
+ if (wild === -1) return {
797
+ cwd: parts.join("/") || ".",
798
+ include: "**/*"
799
+ };
800
+ return {
801
+ cwd: parts.slice(0, wild).join("/") || ".",
802
+ include: parts.slice(wild).join("/")
803
+ };
804
+ }
805
+ /** The project's files a glob matches, sorted, and where they sit. Shared by `glob()` and the build that bundles it. */
806
+ async function collectGlobFiles(rootDir, options) {
807
+ const paths = await resolveGlobPaths(rootDir, options.cwd);
808
+ const include = normalizePatterns(options.include).map(normalizeGlobPattern);
809
+ const ignore = normalizePatterns(options.ignore).map(normalizeGlobPattern);
810
+ const files = await glob$1(include, {
811
+ cwd: paths.cwd,
812
+ dot: options.dot ?? false,
813
+ followSymbolicLinks: options.followSymlinks ?? false,
814
+ ignore: [
815
+ "**/.git/**",
816
+ "**/node_modules/**",
817
+ ...ignore
818
+ ],
819
+ onlyFiles: true
820
+ });
821
+ const matchesInclude = createPathMatcher(include);
822
+ const matchesIgnore = createPathMatcher(ignore);
823
+ let keys = files.map((file) => normalizeSafeSourcePath(file, { allowReserved: true })).filter((file) => matchesInclude(file) && !matchesIgnore(file));
824
+ if (options.followSymlinks) {
825
+ const rooted = [];
826
+ for (const key of keys) if (await resolveRootedGlobFilePath(key, paths, true)) rooted.push(key);
827
+ keys = rooted;
828
+ }
829
+ return {
830
+ paths,
831
+ keys: keys.sort((left, right) => left.localeCompare(right))
832
+ };
833
+ }
834
+ /** Where a key's file is, or undefined when glob() would not read it (a symbolic link it does not follow, say). */
835
+ function globFilePath(key, paths, followSymlinks) {
836
+ return resolveRootedGlobFilePath(key, paths, followSymlinks);
837
+ }
838
+ /**
839
+ * Project files that match a pattern, such as `glob("content/docs/**\/*.md")`. Under `vite dev` they are read from
840
+ * disk, so new files show up at once. A ViteHub build bundles a call with literal options into the server, so hosts
841
+ * without a file system, such as Cloudflare Workers, serve the same files.
842
+ */
843
+ function glob(input) {
844
+ const options = resolveGlobInput(input);
845
+ const caches = /* @__PURE__ */ new WeakMap();
846
+ function cacheFor(ctx) {
847
+ let cache = caches.get(ctx);
848
+ if (!cache) {
849
+ cache = {};
850
+ caches.set(ctx, cache);
851
+ }
852
+ return cache;
853
+ }
854
+ async function getContextKey(ctx) {
855
+ const { root, cwd } = await resolveGlobPaths(resolveSourceRoot(ctx), options.cwd);
856
+ return `${root}\0${cwd}`;
857
+ }
858
+ async function loadKeys(ctx) {
859
+ return (await collectGlobFiles(resolveSourceRoot(ctx), options)).keys;
860
+ }
861
+ async function refreshListing(ctx) {
862
+ const key = await getContextKey(ctx);
863
+ const keys = await loadKeys(ctx);
864
+ const listing = {
865
+ keys,
866
+ keySet: new Set(keys)
867
+ };
868
+ cacheFor(ctx).latest = {
869
+ key,
870
+ listing
871
+ };
872
+ return listing;
873
+ }
874
+ async function getCachedListing(ctx) {
875
+ if (options.keyCache === false) return await refreshListing(ctx);
876
+ const key = await getContextKey(ctx);
877
+ const cache = cacheFor(ctx);
878
+ if (!cache.snapshot || cache.snapshot.key !== key) {
879
+ const listing = refreshListing(ctx);
880
+ const entry = {
881
+ key,
882
+ listing
883
+ };
884
+ cache.snapshot = entry;
885
+ listing.catch(() => {
886
+ if (cache.snapshot === entry) cache.snapshot = void 0;
887
+ });
888
+ }
889
+ return await cache.snapshot.listing;
890
+ }
891
+ async function getKnownListing(ctx) {
892
+ const key = await getContextKey(ctx);
893
+ const { latest } = cacheFor(ctx);
894
+ if (latest?.key === key) return latest.listing;
895
+ return await getCachedListing(ctx);
896
+ }
897
+ async function assertKey(key, ctx) {
898
+ if ((await getKnownListing(ctx)).keySet.has(key)) return;
899
+ if (options.keyCache !== false) throw missingKeyError(key);
900
+ if ((await refreshListing(ctx)).keySet.has(key)) return;
901
+ throw missingKeyError(key);
902
+ }
903
+ async function resolveGlobFilePath(key, ctx) {
904
+ const path = await resolveRootedGlobFilePath(key, await resolveGlobPaths(resolveSourceRoot(ctx), options.cwd), options.followSymlinks === true);
905
+ if (!path) throw missingKeyError(key);
906
+ return path;
907
+ }
908
+ return {
909
+ name: "glob",
910
+ async prepare(ctx) {
911
+ cacheFor(ctx).snapshot = void 0;
912
+ await getCachedListing(ctx);
913
+ },
914
+ async getKeys(ctx) {
915
+ return (await getCachedListing(ctx)).keys.slice();
916
+ },
917
+ async getMeta(key, ctx) {
918
+ await assertKey(key, ctx);
919
+ const { stat } = await import("node:fs/promises");
920
+ const info = await stat(await resolveGlobFilePath(key, ctx));
921
+ return { digest: `${info.size}:${info.mtimeMs}` };
922
+ },
923
+ async getItem(key, ctx) {
924
+ await assertKey(key, ctx);
925
+ const { readFile, stat } = await import("node:fs/promises");
926
+ const filePath = await resolveGlobFilePath(key, ctx);
927
+ const prefix = normalizeSafeSourcePath(options.prefix || "", { allowEmpty: true });
928
+ const bytes = await readFile(filePath);
929
+ const info = await stat(filePath);
930
+ return {
931
+ key,
932
+ path: normalizeSourcePath(prefix ? `${prefix}/${key}` : key),
933
+ content: new Uint8Array(bytes),
934
+ metadata: { mtime: info.mtimeMs }
935
+ };
936
+ }
937
+ };
938
+ }
939
+ function missingKeyError(key) {
940
+ return sourceError(`[vitehub] glob could not find ${JSON.stringify(key)}.`);
941
+ }
942
+ function normalizePatterns(patterns) {
943
+ if (!patterns) return [];
944
+ return Array.isArray(patterns) ? patterns : [String(patterns)];
945
+ }
946
+ function normalizeGlobPattern(pattern) {
947
+ return pattern.replaceAll("\\", "/");
948
+ }
949
+ function resolveSourceRoot(ctx) {
950
+ return ctx.sourceRootDir || ctx.rootDir;
951
+ }
952
+ async function resolveGlobPaths(rootDir, cwd = ".") {
953
+ const { realpath } = await import("node:fs/promises");
954
+ const { isAbsolute, relative, resolve, sep } = await import("node:path");
955
+ const resolvedRoot = await realpath(resolve(rootDir));
956
+ const normalizedCwd = isAbsolute(cwd) ? cwd : normalizeSafeSourcePath(cwd === "." ? "" : cwd, { allowEmpty: true });
957
+ const resolvedCwd = await realpath(isAbsolute(normalizedCwd) ? resolve(normalizedCwd) : resolve(resolvedRoot, normalizedCwd));
958
+ const rel = relative(resolvedRoot, resolvedCwd);
959
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw sourceError(`[vitehub] glob cwd escapes the source root: ${JSON.stringify(cwd)}.`);
960
+ return {
961
+ root: resolvedRoot,
962
+ cwd: resolvedCwd
963
+ };
964
+ }
965
+ async function resolveRootedGlobFilePath(key, paths, followSymlinks) {
966
+ const { lstat, realpath } = await import("node:fs/promises");
967
+ const { isAbsolute, relative, resolve, sep } = await import("node:path");
968
+ const safeKey = normalizeSafeSourcePath(key, { allowReserved: true });
969
+ const path = resolve(paths.cwd, safeKey);
970
+ if (followSymlinks) {
971
+ let target;
972
+ try {
973
+ target = await realpath(path);
974
+ } catch (error) {
975
+ if (isUnavailablePathError(error)) return;
976
+ throw error;
977
+ }
978
+ const rel = relative(paths.root, target);
979
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return;
980
+ return target;
981
+ }
982
+ let current = paths.cwd;
983
+ for (const part of safeKey.split("/")) {
984
+ current = resolve(current, part);
985
+ if ((await lstat(current)).isSymbolicLink()) return;
986
+ }
987
+ return path;
988
+ }
989
+ function isUnavailablePathError(error) {
990
+ return error instanceof Error && ["ENOENT", "ELOOP"].includes(String(Reflect.get(error, "code")));
991
+ }
992
+ //#endregion
993
+ export { resolveGlobInput as i, glob as n, globFilePath as r, collectGlobFiles as t };