@vite-hub/source 0.0.4 → 0.3.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 (52) hide show
  1. package/README.md +267 -96
  2. package/dist/client.d.ts +27 -10
  3. package/dist/client.js +99 -15
  4. package/dist/collection-B8sgxw5-.d.ts +290 -0
  5. package/dist/collection-C0Rvrx3p.js +297 -0
  6. package/dist/collection-route-BplWPxHR.js +10 -0
  7. package/dist/drizzle.d.ts +48 -0
  8. package/dist/drizzle.js +87 -0
  9. package/dist/error-diagnostics-ClQKdi7c.js +194 -0
  10. package/dist/github-D5S0dEZe.js +1312 -0
  11. package/dist/{glob.js → glob-DmdMVqjx.js} +154 -57
  12. package/dist/index.d.ts +284 -62
  13. package/dist/index.js +583 -29
  14. package/dist/invariant-DolT9EEx.js +22 -0
  15. package/dist/mcp.d.ts +3 -4
  16. package/dist/mcp.js +184 -5917
  17. package/dist/object-CtSHeGQO.js +17 -0
  18. package/dist/{path-CUhvUREm.js → path-DFlSryRA.js} +90 -40
  19. package/dist/root-DJNmqCEW.js +11 -0
  20. package/dist/server.d.ts +24 -11
  21. package/dist/server.js +97 -26
  22. package/dist/types-Ln-FxVFn.d.ts +98 -0
  23. package/dist/vite.d.ts +202 -14
  24. package/dist/vite.js +1683 -122
  25. package/package.json +55 -58
  26. package/dist/auth-Ddw55OUG.js +0 -1261
  27. package/dist/client-CDfTmtQu.js +0 -7903
  28. package/dist/collection-B8pXGM2d.js +0 -141
  29. package/dist/collection-CF2ON__k.d.ts +0 -92
  30. package/dist/collection-route-Dw7QLFyx.js +0 -6
  31. package/dist/content/client.d.ts +0 -3
  32. package/dist/content/client.js +0 -2
  33. package/dist/content.d.ts +0 -44
  34. package/dist/content.js +0 -157
  35. package/dist/file-BSWQg9Qv.js +0 -503
  36. package/dist/file-EQ3AjVM6.d.ts +0 -20
  37. package/dist/file.d.ts +0 -2
  38. package/dist/file.js +0 -2
  39. package/dist/github.d.ts +0 -17
  40. package/dist/github.js +0 -1033
  41. package/dist/glob.d.ts +0 -15
  42. package/dist/markdown.d.ts +0 -7
  43. package/dist/markdown.js +0 -10
  44. package/dist/path-BzmU4Eni.js +0 -36
  45. package/dist/registry-C8skfCSV.js +0 -120
  46. package/dist/sse-CE9Q2JqM.js +0 -407
  47. package/dist/streamableHttp-BszaXLmg.js +0 -491
  48. package/dist/types-AIBmt_m6.js +0 -6275
  49. package/dist/types-Bu3WvNX9.d.ts +0 -71
  50. package/tsconfig.vite.json +0 -6
  51. package/types/source/fallback.d.ts +0 -1
  52. package/types/source/index.d.ts +0 -1
@@ -0,0 +1,17 @@
1
+ //#region ../internal/src/object.ts
2
+ /** A non-null object that is not an array. Functions do not pass. */
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /** A non-null object or a function that is not an array. */
7
+ function isRecordOrFunction(value) {
8
+ return Object(value) === value && !Array.isArray(value);
9
+ }
10
+ function isPlainRecord(value) {
11
+ if (!isRecord(value)) return false;
12
+ const prototype = Object.getPrototypeOf(value);
13
+ if (prototype === null) return true;
14
+ return Object.getPrototypeOf(prototype) === null && Object.hasOwn(prototype, "constructor") && prototype.constructor?.name === "Object";
15
+ }
16
+ //#endregion
17
+ export { isRecord as n, isRecordOrFunction as r, isPlainRecord as t };
@@ -1,4 +1,4 @@
1
- import { r as normalizeSourcePath } from "./path-BzmU4Eni.js";
1
+ import { ViteHubError } from "@vite-hub/runtime";
2
2
  //#region \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -17,12 +17,42 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
21
21
  value: mod,
22
22
  enumerable: true
23
23
  }) : target, mod));
24
24
  //#endregion
25
- //#region ../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/lib/constants.js
25
+ //#region src/core/errors.ts
26
+ function sourceError(message, options) {
27
+ return new ViteHubError("SOURCE_FAILED", message, options);
28
+ }
29
+ function sourceNotFoundError(name) {
30
+ return new ViteHubError("SOURCE_NOT_FOUND", `[vitehub] Source "${name}" is not registered.`, { details: { name } });
31
+ }
32
+ function sourcePathError(path) {
33
+ const publicPath = path.slice(0, 4096);
34
+ return new ViteHubError("SOURCE_PATH_INVALID", `[vitehub] Source path escapes the source root: ${JSON.stringify(publicPath)}.`, { details: { path: publicPath } });
35
+ }
36
+ //#endregion
37
+ //#region src/core/path.ts
38
+ function normalizeSourcePath(path = "") {
39
+ return path.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\/+$/, "");
40
+ }
41
+ function normalizeSafeSourcePath(path = "", options = {}) {
42
+ const raw = path.replace(/\\/g, "/");
43
+ const normalized = normalizeSourcePath(path);
44
+ const parts = normalized.split("/").filter(Boolean);
45
+ if (!options.allowEmpty && !normalized) throw sourcePathError(path);
46
+ if (raw.startsWith("/") || /^[a-z]:/i.test(raw) || raw.includes("\0") || parts.some((part) => part === "." || part === "..")) throw sourcePathError(path);
47
+ if (!options.allowReserved && (parts[0] === ".git" || parts[0] === ".vitehub")) throw sourcePathError(path);
48
+ return normalized;
49
+ }
50
+ function decodeSourceContent(content, options) {
51
+ if (options?.encoding === "binary") return typeof content === "string" ? new TextEncoder().encode(content) : content;
52
+ return typeof content === "string" ? content : new TextDecoder().decode(content);
53
+ }
54
+ //#endregion
55
+ //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/constants.js
26
56
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
27
57
  const WIN_SLASH = "\\\\/";
28
58
  const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
@@ -77,7 +107,7 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
77
107
  };
78
108
  module.exports = {
79
109
  DEFAULT_MAX_EXTGLOB_RECURSION,
80
- MAX_LENGTH: 1024 * 64,
110
+ MAX_LENGTH: 65536,
81
111
  POSIX_REGEX_SOURCE: {
82
112
  __proto__: null,
83
113
  alnum: "a-zA-Z0-9",
@@ -191,7 +221,7 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
191
221
  };
192
222
  }));
193
223
  //#endregion
194
- //#region ../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/lib/utils.js
224
+ //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/utils.js
195
225
  var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
196
226
  const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
197
227
  exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
@@ -239,7 +269,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
239
269
  };
240
270
  }));
241
271
  //#endregion
242
- //#region ../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/lib/scan.js
272
+ //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/scan.js
243
273
  var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
244
274
  const utils = require_utils();
245
275
  const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
@@ -268,7 +298,7 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
268
298
  const scan = (input, options) => {
269
299
  const opts = options || {};
270
300
  const length = input.length - 1;
271
- const scanToEnd = opts.parts === true || opts.scanToEnd === true;
301
+ const scanToEnd = opts.parts === true || opts.tokens === true || opts.scanToEnd === true;
272
302
  const slashes = [];
273
303
  const tokens = [];
274
304
  const parts = [];
@@ -371,14 +401,18 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
371
401
  finished = true;
372
402
  if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
373
403
  if (scanToEnd === true) {
404
+ let parens = 0;
374
405
  while (eos() !== true && (code = advance())) {
375
406
  if (code === CHAR_BACKWARD_SLASH) {
376
407
  backslashes = token.backslashes = true;
377
- code = advance();
408
+ advance();
378
409
  continue;
379
410
  }
380
- if (code === CHAR_RIGHT_PARENTHESES) {
381
- isGlob = token.isGlob = true;
411
+ if (code === CHAR_LEFT_PARENTHESES) {
412
+ parens++;
413
+ continue;
414
+ }
415
+ if (code === CHAR_RIGHT_PARENTHESES && --parens === 0) {
382
416
  finished = true;
383
417
  break;
384
418
  }
@@ -426,13 +460,18 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
426
460
  if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
427
461
  isGlob = token.isGlob = true;
428
462
  if (scanToEnd === true) {
463
+ let parens = 1;
429
464
  while (eos() !== true && (code = advance())) {
430
- if (code === CHAR_LEFT_PARENTHESES) {
465
+ if (code === CHAR_BACKWARD_SLASH) {
431
466
  backslashes = token.backslashes = true;
432
- code = advance();
467
+ advance();
433
468
  continue;
434
469
  }
435
- if (code === CHAR_RIGHT_PARENTHESES) {
470
+ if (code === CHAR_LEFT_PARENTHESES) {
471
+ parens++;
472
+ continue;
473
+ }
474
+ if (code === CHAR_RIGHT_PARENTHESES && --parens === 0) {
436
475
  finished = true;
437
476
  break;
438
477
  }
@@ -495,7 +534,7 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
495
534
  if (opts.parts === true || opts.tokens === true) {
496
535
  let prevIndex;
497
536
  for (let idx = 0; idx < slashes.length; idx++) {
498
- const n = prevIndex ? prevIndex + 1 : start;
537
+ const n = prevIndex !== void 0 ? prevIndex + 1 : start;
499
538
  const i = slashes[idx];
500
539
  const value = input.slice(n, i);
501
540
  if (opts.tokens) {
@@ -506,18 +545,19 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
506
545
  depth(tokens[idx]);
507
546
  state.maxDepth += tokens[idx].depth;
508
547
  }
509
- if (idx !== 0 || value !== "") parts.push(value);
510
- prevIndex = i;
511
- }
512
- if (prevIndex && prevIndex + 1 < input.length) {
513
- const value = input.slice(prevIndex + 1);
514
- parts.push(value);
515
- if (opts.tokens) {
516
- tokens[tokens.length - 1].value = value;
517
- depth(tokens[tokens.length - 1]);
518
- state.maxDepth += tokens[tokens.length - 1].depth;
548
+ if (i >= start) {
549
+ parts.push(value);
550
+ prevIndex = i;
519
551
  }
520
552
  }
553
+ const n = prevIndex !== void 0 ? prevIndex + 1 : start;
554
+ const value = input.slice(n);
555
+ parts.push(value);
556
+ if (opts.tokens && prevIndex && prevIndex + 1 < input.length) {
557
+ tokens[tokens.length - 1].value = value;
558
+ depth(tokens[tokens.length - 1]);
559
+ state.maxDepth += tokens[tokens.length - 1].depth;
560
+ }
521
561
  state.slashes = slashes;
522
562
  state.parts = parts;
523
563
  }
@@ -526,7 +566,7 @@ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
526
566
  module.exports = scan;
527
567
  }));
528
568
  //#endregion
529
- //#region ../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/lib/parse.js
569
+ //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/parse.js
530
570
  var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
531
571
  const constants = require_constants();
532
572
  const utils = require_utils();
@@ -890,7 +930,8 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
890
930
  };
891
931
  const extglobClose = (token) => {
892
932
  const literal = input.slice(token.startIndex, state.index + 1);
893
- const analysis = analyzeRepeatedExtglob(input.slice(token.startIndex + 2, state.index), opts);
933
+ const body = input.slice(token.startIndex + 2, state.index);
934
+ const analysis = analyzeRepeatedExtglob(body, opts);
894
935
  if ((token.type === "plus" || token.type === "star") && analysis.risky) {
895
936
  const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0;
896
937
  const open = tokens[token.tokensIndex];
@@ -955,10 +996,12 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
955
996
  }
956
997
  return esc ? m : `\\${m}`;
957
998
  });
958
- if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
959
- else output = output.replace(/\\+/g, (m) => {
960
- return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
961
- });
999
+ if (backslashes === true) {
1000
+ if (opts.unescape === true) output = output.replace(/\\/g, "");
1001
+ else output = output.replace(/\\+/g, (m) => {
1002
+ return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
1003
+ });
1004
+ }
962
1005
  if (output === input && opts.contains === true) {
963
1006
  state.output = input;
964
1007
  return state;
@@ -1016,7 +1059,8 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1016
1059
  if (inner.includes(":")) {
1017
1060
  const idx = prev.value.lastIndexOf("[");
1018
1061
  const pre = prev.value.slice(0, idx);
1019
- const posix = POSIX_REGEX_SOURCE[prev.value.slice(idx + 2)];
1062
+ const rest = prev.value.slice(idx + 2);
1063
+ const posix = POSIX_REGEX_SOURCE[rest];
1020
1064
  if (posix) {
1021
1065
  prev.value = pre + posix;
1022
1066
  state.backtrack = true;
@@ -1424,6 +1468,7 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1424
1468
  rest = rest.slice(3);
1425
1469
  consume("/**", 3);
1426
1470
  }
1471
+ const isEnd = eos() || state.parens > 0 && rest === ")".repeat(state.parens) && !extglobs.some((extglob) => extglob.type === "negate");
1427
1472
  if (prior.type === "bos" && eos()) {
1428
1473
  prev.type = "globstar";
1429
1474
  prev.value += value;
@@ -1433,7 +1478,7 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1433
1478
  consume(value);
1434
1479
  continue;
1435
1480
  }
1436
- if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1481
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && isEnd) {
1437
1482
  state.output = state.output.slice(0, -(prior.output + prev.output).length);
1438
1483
  prior.output = `(?:${prior.output}`;
1439
1484
  prev.type = "globstar";
@@ -1598,7 +1643,7 @@ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1598
1643
  module.exports = parse;
1599
1644
  }));
1600
1645
  //#endregion
1601
- //#region ../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/lib/picomatch.js
1646
+ //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/lib/picomatch.js
1602
1647
  var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1603
1648
  const scan = require_scan();
1604
1649
  const parse = require_parse();
@@ -1728,8 +1773,10 @@ var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1728
1773
  output = format ? format(input) : input;
1729
1774
  match = output === glob;
1730
1775
  }
1731
- if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch.matchBase(input, regex, options, posix);
1732
- else match = regex.exec(output);
1776
+ if (match === false || opts.capture === true) {
1777
+ if (opts.matchBase === true || opts.basename === true) match = picomatch.matchBase(input, regex, options, posix);
1778
+ else match = regex.exec(output);
1779
+ }
1733
1780
  return {
1734
1781
  isMatch: Boolean(match),
1735
1782
  match,
@@ -1910,7 +1957,7 @@ var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1910
1957
  module.exports = picomatch;
1911
1958
  }));
1912
1959
  //#endregion
1913
- //#region ../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js
1960
+ //#region ../../node_modules/.pnpm/picomatch@4.0.7/node_modules/picomatch/index.js
1914
1961
  var require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1915
1962
  const pico = require_picomatch$1();
1916
1963
  const utils = require_utils();
@@ -1927,10 +1974,13 @@ var require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1927
1974
  //#endregion
1928
1975
  //#region src/sources/path.ts
1929
1976
  var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
1977
+ function createPathMatcher(patterns) {
1978
+ if (!patterns) return () => true;
1979
+ const match = (0, import_picomatch.default)((Array.isArray(patterns) ? patterns : [String(patterns)]).map((pattern) => normalizeSourcePath(pattern)), { dot: true });
1980
+ return (path) => match(normalizeSourcePath(path));
1981
+ }
1930
1982
  function matchesAny(path, patterns) {
1931
- if (!patterns) return true;
1932
- const list = Array.isArray(patterns) ? patterns : [String(patterns)];
1933
- return import_picomatch.default.isMatch(normalizeSourcePath(path), list.map((pattern) => normalizeSourcePath(pattern)), { dot: true });
1983
+ return createPathMatcher(patterns)(path);
1934
1984
  }
1935
1985
  //#endregion
1936
- export { __toESM as i, require_picomatch as n, __commonJSMin as r, matchesAny as t };
1986
+ export { normalizeSafeSourcePath as a, sourceNotFoundError as c, decodeSourceContent as i, sourcePathError as l, matchesAny as n, normalizeSourcePath as o, require_picomatch as r, sourceError as s, createPathMatcher as t, __toESM as u };
@@ -0,0 +1,11 @@
1
+ import { a as normalizeSafeSourcePath } from "./path-DFlSryRA.js";
2
+ //#region src/sources/github/root.ts
3
+ function normalizeGitHubRoot(path = "") {
4
+ const root = path.replace(/\\/g, "/").split("/").filter((part) => part !== ".").join("/");
5
+ return normalizeSafeSourcePath(root, {
6
+ allowEmpty: true,
7
+ allowReserved: true
8
+ }).split("/").filter(Boolean).join("/");
9
+ }
10
+ //#endregion
11
+ export { normalizeGitHubRoot as t };
package/dist/server.d.ts CHANGED
@@ -1,15 +1,28 @@
1
- import { n as Collection } from "./collection-CF2ON__k.js";
2
-
1
+ import { r as Collection } from "./collection-B8sgxw5-.js";
2
+ import { AccessAuthorizeOption, ViteHubContext } from "@vite-hub/runtime";
3
+ import { CacheOptions } from "ocache";
4
+ //#region src/cached-source.d.ts
5
+ interface KeyedSourceReader {
6
+ get(key: never): Promise<unknown>;
7
+ }
8
+ type ValidCachedGet<TReader extends KeyedSourceReader> = (<T>() => T extends TReader["get"] ? 1 : 2) extends (<T>() => T extends ((key: Parameters<TReader["get"]>[0]) => ReturnType<TReader["get"]>) ? 1 : 2) ? unknown : never;
9
+ type SourceReaderCacheOptions<TKey, TValue> = Omit<CacheOptions<TValue, [key: TKey]>, "name"> & {
10
+ name: string;
11
+ };
12
+ /** Cache `get(key)` in the Nitro `cache` storage. Other reader operations pass through unchanged. */
13
+ export declare function cachedSource<const TReader extends KeyedSourceReader>(reader: TReader & ValidCachedGet<TReader>, options: SourceReaderCacheOptions<Parameters<TReader["get"]>[0], Awaited<ReturnType<TReader["get"]>>>): TReader;
14
+ //#endregion
3
15
  //#region src/server.d.ts
4
- interface CollectionHandler {
5
- (event: unknown): Promise<unknown>;
6
- fetch(input: Request | URL | string): Promise<Response>;
16
+ /** A Collection route as a Fetchable. Mount it as a Nitro route, or call `fetch()` with a Web Request. */
17
+ export interface CollectionHandler {
18
+ fetch(request: Request): Promise<Response>;
7
19
  }
8
- interface CollectionHandlerEvent {
9
- req: {
10
- signal: AbortSignal;
11
- };
20
+ /** Wraps a Collection handler so it runs only after the request is authorized. Return a `Response` to reject the request. */
21
+ export type CollectionAuthorizationGuard = <TResult>(authorize: AccessAuthorizeOption<Request & ViteHubContext>, handler: (request: Request) => Promise<TResult>) => (request: Request) => Promise<TResult | Response>;
22
+ export interface CollectionHandlerOptions {
23
+ /** Required unless the Collection sets `access: "public"`. Generated routes pass Auth's `withAuthorization`. */
24
+ withAuthorization?: CollectionAuthorizationGuard;
12
25
  }
13
- declare function defineCollectionHandler<TItem, TQuery extends object, TQueryInput extends object>(collection: Collection<TItem, TQuery, TQueryInput>): CollectionHandler;
26
+ export declare function defineCollectionHandler<TItem, TQuery extends object, TQueryInput extends object>(collection: Collection<TItem, TQuery, TQueryInput>, options?: CollectionHandlerOptions): CollectionHandler;
14
27
  //#endregion
15
- export { CollectionHandler, CollectionHandlerEvent, defineCollectionHandler };
28
+ export type { SourceReaderCacheOptions };
package/dist/server.js CHANGED
@@ -1,28 +1,78 @@
1
- import { t as CollectionCursorError } from "./collection-B8pXGM2d.js";
2
- import { createError, defineEventHandler, getQuery } from "h3";
1
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-ClQKdi7c.js";
2
+ import { r as CollectionCursorError, t as assertCollectionAccess } from "./collection-C0Rvrx3p.js";
3
+ //#region src/cached-source.ts
4
+ /** Cache `get(key)` in the Nitro `cache` storage. Other reader operations pass through unchanged. */
5
+ function cachedSource(reader, options) {
6
+ let cachedGet;
7
+ const get = reader.get;
8
+ async function readCached(key) {
9
+ cachedGet ??= import("nitro/cache").then(({ defineCachedFunction }) => defineCachedFunction((value) => get.call(reader, value), {
10
+ swr: false,
11
+ ...options
12
+ })).catch((error) => {
13
+ cachedGet = void 0;
14
+ throw error;
15
+ });
16
+ return await (await cachedGet)(key);
17
+ }
18
+ const facade = Object.create(reader);
19
+ return new Proxy(facade, {
20
+ get(_target, property) {
21
+ if (property === "get") return readCached;
22
+ const value = Reflect.get(reader, property, reader);
23
+ return typeof value === "function" ? value.bind(reader) : value;
24
+ },
25
+ set(_target, property, value) {
26
+ return Reflect.set(reader, property, value, reader);
27
+ },
28
+ ownKeys() {
29
+ return Reflect.ownKeys(reader);
30
+ },
31
+ getOwnPropertyDescriptor(_target, property) {
32
+ const descriptor = Reflect.getOwnPropertyDescriptor(reader, property);
33
+ return descriptor ? {
34
+ ...descriptor,
35
+ configurable: true
36
+ } : void 0;
37
+ }
38
+ });
39
+ }
40
+ //#endregion
3
41
  //#region src/server.ts
42
+ /** The query of a request URL. A parameter that the URL repeats becomes an array, as in H3's `getQuery()`. */
43
+ function requestQuery(request) {
44
+ const query = /* @__PURE__ */ new Map();
45
+ for (const [key, value] of new URL(request.url).searchParams) {
46
+ const current = query.get(key);
47
+ query.set(key, current === void 0 ? value : [...Array.isArray(current) ? current : [current], value]);
48
+ }
49
+ return Object.fromEntries(query);
50
+ }
4
51
  function queryValue(query, key) {
5
52
  const value = query[key];
6
- if (Array.isArray(value)) throw new TypeError(`[vitehub] Collection query parameter ${JSON.stringify(key)} must have one value.`);
53
+ if (Array.isArray(value)) throw sourceErrorDiagnostics.SOURCE_R0011({ message: `[vitehub] Collection query parameter ${JSON.stringify(key)} must have one value.` });
7
54
  return value;
8
55
  }
9
56
  function queryLimit(query) {
10
57
  const value = queryValue(query, "limit");
11
58
  if (value === void 0) return;
12
- if (!/^\d+$/.test(value)) throw new TypeError("[vitehub] Collection limit must be a positive integer.");
59
+ if (!/^\d+$/.test(value)) throw sourceErrorDiagnostics.SOURCE_R0012({ message: "[vitehub] Collection limit must be a positive integer." });
13
60
  const limit = Number(value);
14
- if (!Number.isSafeInteger(limit) || limit < 1) throw new TypeError("[vitehub] Collection limit must be a positive integer.");
61
+ if (!Number.isSafeInteger(limit) || limit < 1) throw sourceErrorDiagnostics.SOURCE_R0013({ message: "[vitehub] Collection limit must be a positive integer." });
15
62
  return limit;
16
63
  }
17
64
  function collectionQuery(query) {
18
65
  return Object.fromEntries(Object.entries(query).filter(([key]) => key !== "cursor" && key !== "limit"));
19
66
  }
67
+ /** An error Response with the `status` and `message` fields of an H3 error body. */
68
+ function errorResponse(status, message) {
69
+ return Response.json({
70
+ status,
71
+ message
72
+ }, { status });
73
+ }
20
74
  function invalidRequest(cause) {
21
- throw createError({
22
- cause,
23
- statusCode: 400,
24
- statusMessage: cause instanceof Error ? cause.message : "Invalid collection request."
25
- });
75
+ return errorResponse(400, cause instanceof Error ? cause.message : "Invalid collection request.");
26
76
  }
27
77
  function isJSONContainer(value) {
28
78
  return Object(value) === value && !(value instanceof Function);
@@ -31,41 +81,62 @@ function serializeCollectionPage(value) {
31
81
  const serialized = JSON.stringify(value, (_key, entry) => {
32
82
  if (!isJSONContainer(entry) || Array.isArray(entry)) return entry;
33
83
  const prototype = Object.getPrototypeOf(entry);
34
- if (prototype !== null && Object.getPrototypeOf(prototype) !== null) throw new TypeError("[vitehub] Collection pages may only contain plain objects, arrays, and toJSON() values. Use transform() for class instances and other object types.");
84
+ if (prototype !== null && Object.getPrototypeOf(prototype) !== null) throw sourceErrorDiagnostics.SOURCE_R0014({ message: "[vitehub] Collection pages may only contain plain objects, arrays, and toJSON() values. Use transform() for class instances and other object types." });
35
85
  return entry;
36
86
  });
37
- if (serialized === void 0) throw new TypeError("[vitehub] Collection page is not JSON-serializable.");
87
+ if (serialized === void 0) throw sourceErrorDiagnostics.SOURCE_R0015({ message: "[vitehub] Collection page is not JSON-serializable." });
38
88
  return JSON.parse(serialized);
39
89
  }
90
+ function isCallable(value) {
91
+ return typeof value === "function" || typeof value === "undefined" && value !== void 0;
92
+ }
93
+ function hasDeclaredMethod(value, key) {
94
+ const object = Object(value);
95
+ if (Object.hasOwn(object, key)) return isCallable(Reflect.get(object, key));
96
+ let prototype = Object.getPrototypeOf(object);
97
+ while (prototype && prototype !== Object.prototype) {
98
+ if (Object.hasOwn(prototype, key)) {
99
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
100
+ return isCallable(constructor) && constructor !== Object && constructor.prototype === prototype && isCallable(Reflect.get(object, key));
101
+ }
102
+ prototype = Object.getPrototypeOf(prototype);
103
+ }
104
+ return false;
105
+ }
40
106
  function assertCollection(value) {
41
- if (Object(value) !== value || !(Reflect.get(Object(value), "page") instanceof Function) || !(Reflect.get(Object(value), "parseQuery") instanceof Function)) throw new TypeError("[vitehub] defineCollectionHandler() requires a Collection.");
107
+ if (Object(value) !== value || !hasDeclaredMethod(Object(value), "page") || !hasDeclaredMethod(Object(value), "parseQuery")) throw sourceErrorDiagnostics.SOURCE_R0016({ message: "[vitehub] defineCollectionHandler() requires a Collection." });
42
108
  }
43
- function defineCollectionHandler(collection) {
109
+ function defineCollectionHandler(collection, options = {}) {
44
110
  assertCollection(collection);
45
- return defineEventHandler(async (event) => {
46
- const requestQuery = getQuery(event);
111
+ if (collection.route === false) return { fetch: async () => errorResponse(404, "Not Found") };
112
+ const { authorize } = assertCollectionAccess(collection);
113
+ const { withAuthorization } = options;
114
+ if (authorize && !withAuthorization) throw sourceErrorDiagnostics.SOURCE_R0025({ message: "[vitehub] Collection authorize requires Auth. Enable Auth and add `server/auth.ts`." });
115
+ const handlePage = async (request) => {
116
+ const parameters = requestQuery(request);
47
117
  let cursor;
48
118
  let limit;
49
119
  let query;
50
120
  try {
51
- cursor = queryValue(requestQuery, "cursor");
52
- limit = queryLimit(requestQuery);
53
- query = await collection.parseQuery(collectionQuery(requestQuery));
121
+ cursor = queryValue(parameters, "cursor");
122
+ limit = queryLimit(parameters);
123
+ query = await collection.parseQuery(collectionQuery(parameters));
54
124
  } catch (cause) {
55
- invalidRequest(cause);
125
+ return invalidRequest(cause);
56
126
  }
57
127
  try {
58
- return serializeCollectionPage(await collection.page({
128
+ return Response.json(serializeCollectionPage(await collection.page({
59
129
  cursor,
60
130
  limit,
61
131
  query,
62
- signal: event.req.signal
63
- }));
132
+ signal: request.signal
133
+ })));
64
134
  } catch (cause) {
65
- if (cause instanceof CollectionCursorError) invalidRequest(cause);
135
+ if (cause instanceof CollectionCursorError) return cause.reason === "stale" ? errorResponse(409, cause.message) : invalidRequest(cause);
66
136
  throw cause;
67
137
  }
68
- });
138
+ };
139
+ return { fetch: authorize && withAuthorization ? withAuthorization(authorize, handlePage) : handlePage };
69
140
  }
70
141
  //#endregion
71
- export { defineCollectionHandler };
142
+ export { cachedSource, defineCollectionHandler };
@@ -0,0 +1,98 @@
1
+ //#region src/core/types.d.ts
2
+ type SourceContent = string | Uint8Array;
3
+ interface ReadSourceOptions {
4
+ encoding?: "utf8" | "binary";
5
+ }
6
+ type ReadSourceResult<TOptions extends ReadSourceOptions | undefined = undefined> = TOptions extends {
7
+ encoding: "binary";
8
+ } ? Uint8Array : string;
9
+ interface SourceContext {
10
+ abortSignal?: AbortSignal;
11
+ revision?: SourceRevision;
12
+ rootDir: string;
13
+ sourceRootDir?: string;
14
+ source?: string;
15
+ workspace?: string;
16
+ }
17
+ interface SourceCacheOptions {
18
+ maxAge?: number;
19
+ }
20
+ interface SourceRevision {
21
+ id: string;
22
+ immutable: boolean;
23
+ ref?: string;
24
+ }
25
+ interface SourceItem<TKey extends string = string, TData = unknown, TMetadata extends object = object> {
26
+ key: TKey;
27
+ path?: string;
28
+ content?: SourceContent;
29
+ data?: TData;
30
+ mediaType?: string;
31
+ metadata?: TMetadata;
32
+ }
33
+ interface Source<TKey extends string = string, TData = unknown, TMetadata extends object = object> {
34
+ name: string;
35
+ cache?: false | SourceCacheOptions;
36
+ fingerprint?: unknown;
37
+ resolveRevision?(ctx: SourceContext): Promise<SourceRevision | undefined>;
38
+ prepare?(ctx: SourceContext): Promise<void>;
39
+ getKeys(ctx: SourceContext): Promise<TKey[]>;
40
+ getItem(key: TKey, ctx: SourceContext): Promise<SourceItem<TKey, TData, TMetadata>>;
41
+ getItems?(ctx: SourceContext): Promise<SourceItem<TKey, TData, TMetadata>[]>;
42
+ getMeta?(key: TKey, ctx: SourceContext): Promise<TMetadata | undefined>;
43
+ }
44
+ interface SourceListEntry<TKey extends string = string> {
45
+ key: TKey;
46
+ type: "file" | "directory";
47
+ }
48
+ declare global {
49
+ interface ViteHubSourceMap {}
50
+ }
51
+ interface SourceMap extends ViteHubSourceMap {}
52
+ /** Resolve an optional registered name to its loader definition. */
53
+ type RegisteredSource<TName extends SourceName> = TName extends keyof ViteHubSourceMap ? ViteHubSourceMap[TName] extends Source ? ViteHubSourceMap[TName] : never : Source;
54
+ type SourceName = [keyof ViteHubSourceMap] extends [never] ? string : Extract<keyof ViteHubSourceMap, string>;
55
+ type SourceKeyFunction<TSource extends Source> = TSource extends unknown ? (key: Parameters<TSource["getItem"]>[0]) => void : never;
56
+ /** Keys accepted by every possible definition variant. */
57
+ type SourceKey<TSource extends Source = Source> = SourceKeyFunction<TSource> extends ((key: infer TKey) => void) ? Extract<TKey, string> : never;
58
+ type SourceEntry<TSource extends Source = Source> = Awaited<ReturnType<TSource["getItem"]>>;
59
+ type ItemData<TItem> = TItem extends {
60
+ data?: infer TData;
61
+ } ? TData : never;
62
+ type ItemMetadata<TItem> = TItem extends {
63
+ metadata?: infer TMetadata;
64
+ } ? TMetadata : never;
65
+ type SourceData<TSource extends Source = Source> = ItemData<SourceEntry<TSource>>;
66
+ type SourceMetadata<TSource extends Source = Source> = ItemMetadata<SourceEntry<TSource>>;
67
+ type SourceMeta<TSource extends Source> = TSource extends unknown ? "getMeta" extends keyof TSource ? Awaited<ReturnType<NonNullable<TSource["getMeta"]>>> | (undefined extends TSource["getMeta"] ? undefined : never) : undefined : never;
68
+ type SourceEntries<TSource extends Source> = TSource extends unknown ? "getItems" extends keyof TSource ? Awaited<ReturnType<NonNullable<TSource["getItems"]>>> | (undefined extends TSource["getItems"] ? SourceEntry<TSource>[] : never) : SourceEntry<TSource>[] : never;
69
+ interface SourceFile<TKey extends string = string, TMetadata extends object = Record<string, unknown>> extends SourceItem<TKey, unknown, TMetadata> {
70
+ content: SourceContent;
71
+ }
72
+ /** File loaders guarantee readable content for every item. */
73
+ interface FileSource<TKey extends string = string, TMetadata extends object = Record<string, unknown>> extends Source<TKey, unknown, TMetadata> {
74
+ getItem(key: TKey, ctx: SourceContext): Promise<SourceFile<TKey, TMetadata>>;
75
+ getItems?(ctx: SourceContext): Promise<SourceFile<TKey, TMetadata>[]>;
76
+ }
77
+ /** `file()` and `markdown()` return a Source with one item. `key` is the key of that item. */
78
+ interface SingleFileSource<TKey extends string = string, TMetadata extends object = Record<string, unknown>> extends FileSource<TKey, TMetadata> {
79
+ name: "file";
80
+ key: TKey;
81
+ }
82
+ interface SourceFileMethods<TKey extends string> {
83
+ read<TOptions extends ReadSourceOptions | undefined = undefined>(key: TKey, options?: TOptions): Promise<ReadSourceResult<TOptions>>;
84
+ list(prefix?: string): Promise<SourceListEntry[]>;
85
+ }
86
+ /** A reader owns one revision and preparation attempt. Create another reader to refresh. */
87
+ type SourceReader<TSource extends Source = Source> = {
88
+ revision(): Promise<SourceRevision | undefined>;
89
+ keys(): Promise<Awaited<ReturnType<TSource["getKeys"]>>>;
90
+ get(key: SourceKey<TSource>): Promise<SourceEntry<TSource>>;
91
+ items(): Promise<SourceEntries<TSource>>;
92
+ meta(key: SourceKey<TSource>): Promise<SourceMeta<TSource>>;
93
+ exists(key: SourceKey<TSource>): Promise<boolean>;
94
+ } & (SourceEntry<TSource> extends {
95
+ content: SourceContent;
96
+ } ? SourceFileMethods<SourceKey<TSource>> : object);
97
+ //#endregion
98
+ export { SourceMetadata as _, SingleFileSource as a, SourceRevision as b, SourceContent as c, SourceEntry as d, SourceFile as f, SourceMap as g, SourceListEntry as h, RegisteredSource as i, SourceContext as l, SourceKey as m, ReadSourceOptions as n, Source as o, SourceItem as p, ReadSourceResult as r, SourceCacheOptions as s, FileSource as t, SourceData as u, SourceName as v, SourceReader as y };