@vite-hub/source 0.1.0 → 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 (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/server.js CHANGED
@@ -1,16 +1,6 @@
1
- import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
2
- import { t as CollectionCursorError } from "./collection-cursor-WzV1Jd6v.js";
3
- 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";
4
3
  //#region src/cached-source.ts
5
- function isRuntimeFunction(value) {
6
- if (value === null || Object(value) !== value) return false;
7
- try {
8
- Function.prototype.toString.call(value);
9
- return true;
10
- } catch {
11
- return false;
12
- }
13
- }
14
4
  /** Cache `get(key)` in the Nitro `cache` storage. Other reader operations pass through unchanged. */
15
5
  function cachedSource(reader, options) {
16
6
  let cachedGet;
@@ -19,7 +9,10 @@ function cachedSource(reader, options) {
19
9
  cachedGet ??= import("nitro/cache").then(({ defineCachedFunction }) => defineCachedFunction((value) => get.call(reader, value), {
20
10
  swr: false,
21
11
  ...options
22
- }));
12
+ })).catch((error) => {
13
+ cachedGet = void 0;
14
+ throw error;
15
+ });
23
16
  return await (await cachedGet)(key);
24
17
  }
25
18
  const facade = Object.create(reader);
@@ -27,7 +20,7 @@ function cachedSource(reader, options) {
27
20
  get(_target, property) {
28
21
  if (property === "get") return readCached;
29
22
  const value = Reflect.get(reader, property, reader);
30
- return isRuntimeFunction(value) ? value.bind(reader) : value;
23
+ return typeof value === "function" ? value.bind(reader) : value;
31
24
  },
32
25
  set(_target, property, value) {
33
26
  return Reflect.set(reader, property, value, reader);
@@ -46,6 +39,15 @@ function cachedSource(reader, options) {
46
39
  }
47
40
  //#endregion
48
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
+ }
49
51
  function queryValue(query, key) {
50
52
  const value = query[key];
51
53
  if (Array.isArray(value)) throw sourceErrorDiagnostics.SOURCE_R0011({ message: `[vitehub] Collection query parameter ${JSON.stringify(key)} must have one value.` });
@@ -62,12 +64,15 @@ function queryLimit(query) {
62
64
  function collectionQuery(query) {
63
65
  return Object.fromEntries(Object.entries(query).filter(([key]) => key !== "cursor" && key !== "limit"));
64
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
+ }
65
74
  function invalidRequest(cause) {
66
- throw createError({
67
- cause,
68
- statusCode: 400,
69
- statusMessage: cause instanceof Error ? cause.message : "Invalid collection request."
70
- });
75
+ return errorResponse(400, cause instanceof Error ? cause.message : "Invalid collection request.");
71
76
  }
72
77
  function isJSONContainer(value) {
73
78
  return Object(value) === value && !(value instanceof Function);
@@ -83,12 +88,7 @@ function serializeCollectionPage(value) {
83
88
  return JSON.parse(serialized);
84
89
  }
85
90
  function isCallable(value) {
86
- try {
87
- Reflect.apply(Function.prototype.toString, value, []);
88
- return true;
89
- } catch {
90
- return false;
91
- }
91
+ return typeof value === "function" || typeof value === "undefined" && value !== void 0;
92
92
  }
93
93
  function hasDeclaredMethod(value, key) {
94
94
  const object = Object(value);
@@ -108,42 +108,35 @@ function assertCollection(value) {
108
108
  }
109
109
  function defineCollectionHandler(collection, options = {}) {
110
110
  assertCollection(collection);
111
- if (collection.route === false) throw new TypeError("[vitehub] A server-only Collection cannot be exposed through defineCollectionHandler().");
112
- const { authorize } = collection;
111
+ if (collection.route === false) return { fetch: async () => errorResponse(404, "Not Found") };
112
+ const { authorize } = assertCollectionAccess(collection);
113
113
  const { withAuthorization } = options;
114
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 (event) => {
116
- const requestQuery = getQuery(event);
115
+ const handlePage = async (request) => {
116
+ const parameters = requestQuery(request);
117
117
  let cursor;
118
118
  let limit;
119
119
  let query;
120
120
  try {
121
- cursor = queryValue(requestQuery, "cursor");
122
- limit = queryLimit(requestQuery);
123
- query = await collection.parseQuery(collectionQuery(requestQuery));
121
+ cursor = queryValue(parameters, "cursor");
122
+ limit = queryLimit(parameters);
123
+ query = await collection.parseQuery(collectionQuery(parameters));
124
124
  } catch (cause) {
125
- invalidRequest(cause);
125
+ return invalidRequest(cause);
126
126
  }
127
127
  try {
128
- return serializeCollectionPage(await collection.page({
128
+ return Response.json(serializeCollectionPage(await collection.page({
129
129
  cursor,
130
130
  limit,
131
131
  query,
132
- signal: event.req.signal
133
- }));
132
+ signal: request.signal
133
+ })));
134
134
  } catch (cause) {
135
- if (cause instanceof CollectionCursorError) {
136
- if (cause.reason === "stale") throw createError({
137
- cause,
138
- statusCode: 409,
139
- statusMessage: cause.message
140
- });
141
- invalidRequest(cause);
142
- }
135
+ if (cause instanceof CollectionCursorError) return cause.reason === "stale" ? errorResponse(409, cause.message) : invalidRequest(cause);
143
136
  throw cause;
144
137
  }
145
138
  };
146
- return defineEventHandler(authorize && withAuthorization ? withAuthorization(authorize, handlePage) : handlePage);
139
+ return { fetch: authorize && withAuthorization ? withAuthorization(authorize, handlePage) : handlePage };
147
140
  }
148
141
  //#endregion
149
142
  export { cachedSource, defineCollectionHandler };
@@ -74,6 +74,11 @@ interface FileSource<TKey extends string = string, TMetadata extends object = Re
74
74
  getItem(key: TKey, ctx: SourceContext): Promise<SourceFile<TKey, TMetadata>>;
75
75
  getItems?(ctx: SourceContext): Promise<SourceFile<TKey, TMetadata>[]>;
76
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
+ }
77
82
  interface SourceFileMethods<TKey extends string> {
78
83
  read<TOptions extends ReadSourceOptions | undefined = undefined>(key: TKey, options?: TOptions): Promise<ReadSourceResult<TOptions>>;
79
84
  list(prefix?: string): Promise<SourceListEntry[]>;
@@ -90,4 +95,4 @@ type SourceReader<TSource extends Source = Source> = {
90
95
  content: SourceContent;
91
96
  } ? SourceFileMethods<SourceKey<TSource>> : object);
92
97
  //#endregion
93
- export { SourceName as _, Source as a, SourceContext as c, SourceFile as d, SourceItem as f, SourceMetadata as g, SourceMap as h, RegisteredSource as i, SourceData as l, SourceListEntry as m, ReadSourceOptions as n, SourceCacheOptions as o, SourceKey as p, ReadSourceResult as r, SourceContent as s, FileSource as t, SourceEntry as u, SourceReader as v, SourceRevision as y };
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 };
package/dist/vite.d.ts CHANGED
@@ -25,9 +25,35 @@ interface ViteHubProviderOutputEntry {
25
25
  /** Absolute path. */
26
26
  path: string;
27
27
  }
28
+ /**
29
+ * Where an inspected resource id came from. `name` means the host binds the resource by its name and needs no id.
30
+ * The CLI sets `provider-output` when only a generated Wrangler config names the id.
31
+ */
32
+ type ViteHubResourceIdSource = "config" | "env" | "name" | "provider-output" | "provision-state";
33
+ /** One host resource that a Definition or store maps to. Owner packages read only local config and Provision State. */
34
+ interface ViteHubResourceSummary {
35
+ /** Cloudflare binding name, so the CLI can find the id in generated Wrangler config. */
36
+ binding?: string;
37
+ /** Definition or store name. */
38
+ definition: string;
39
+ /** Env variable that supplied the id when `source` is `env`. */
40
+ env?: string;
41
+ host: "cloudflare" | "vercel";
42
+ id?: string;
43
+ /** Same resource kind names as Provision actions, for example `cloudflare-d1`. */
44
+ kind: string;
45
+ /** Resource name on the host, when the config names it. */
46
+ name?: string;
47
+ /** Explains how the host finds the resource when no id or name is known locally. */
48
+ note?: string;
49
+ owner: string;
50
+ /** Absent when no id is known yet. */
51
+ source?: ViteHubResourceIdSource;
52
+ }
28
53
  interface ViteHubInspectionContributor {
29
54
  definitions?: readonly ViteHubDefinitionInspector[];
30
55
  providerOutput?: readonly ViteHubProviderOutputEntry[];
56
+ resources?: () => readonly ViteHubResourceSummary[] | Promise<readonly ViteHubResourceSummary[]>;
31
57
  }
32
58
  type ViteHubInspectionContributorFactory = () => ViteHubInspectionContributor | undefined | Promise<ViteHubInspectionContributor | undefined>;
33
59
  interface ViteHubInspectionPluginMetadata {
@@ -51,7 +77,14 @@ export declare function inspectCollectionDefinitions(options: CollectionInspecti
51
77
  export type GeneratedSourceHandler = GeneratedSourceRoute | GeneratedSourcePlugin;
52
78
  export interface GeneratedSourceRoute {
53
79
  handler: string;
54
- method?: "get";
80
+ method?: "get" | "post";
81
+ /** Runs for every request and passes through when it does not answer, as Content's `<url>.md` copies do. */
82
+ middleware?: true;
83
+ /**
84
+ * `false` loads the handler when the server starts. Middleware that reads the response of later handlers needs it,
85
+ * because a lazy handler does not receive `next`. Such a handler must load heavy modules itself, on demand.
86
+ */
87
+ lazy?: false;
55
88
  plugin?: never;
56
89
  route: string;
57
90
  }
@@ -60,11 +93,18 @@ export interface GeneratedSourcePlugin {
60
93
  handler: string;
61
94
  method?: never;
62
95
  plugin: true;
96
+ /** Install request interception before an async plugin can let the server accept requests. */
97
+ position?: "start" | "end";
63
98
  route?: never;
64
99
  }
65
100
  export interface SourceGenerationOptions {
66
101
  /** Pass Auth's `withAuthorization` to generated Collection routes. Requires the Auth Vite plugin. */
67
102
  auth?: boolean;
103
+ /** The routes that the app serves for the whole site, with the Content pages, so Content does not add them. */
104
+ appSeo?: {
105
+ sitemap?: boolean;
106
+ robots?: boolean;
107
+ };
68
108
  contentImportBase?: string;
69
109
  importBase?: string;
70
110
  projectRoot: string;
@@ -73,14 +113,18 @@ export interface SourceGenerationOptions {
73
113
  export interface SourceVitePluginOptions {
74
114
  /** Pass Auth's `withAuthorization` to generated Collection routes when the Auth Vite plugin has a Definition. */
75
115
  auth?: boolean | ((input: {
76
- configuredAuth?: boolean;
77
116
  projectRoot: string;
78
117
  serverDirs?: string[];
79
118
  }) => boolean);
119
+ /** The routes that the app serves for the whole site, with the Content pages, so Content does not add them. */
120
+ appSeo?: {
121
+ sitemap?: boolean;
122
+ robots?: boolean;
123
+ };
80
124
  contentImportBase?: string;
81
125
  importBase?: string;
82
126
  }
83
- /** The discovered `server/content.ts` file. It exports the Content runtime as `content`. */
127
+ /** The discovered `server/content.ts` file. Its default export is the Content runtime. */
84
128
  export interface ContentDefinitionFile {
85
129
  handler: string;
86
130
  }
@@ -100,14 +144,18 @@ interface NitroGeneratedConfig {
100
144
  plugins?: unknown[];
101
145
  }
102
146
  interface SourceNitroHost extends NitroRouteGuard {
103
- options: NitroGeneratedConfig;
147
+ options: NitroGeneratedConfig & NonNullable<NitroRouteGuard["options"]>;
104
148
  routing: {
105
149
  sync(): void;
106
150
  };
107
151
  }
108
152
  interface NitroRouteGuard {
153
+ options?: {
154
+ dev?: boolean;
155
+ runtimeConfig?: Record<string, unknown>;
156
+ };
109
157
  hooks: {
110
- hook(name: "build:before", callback: () => void): void;
158
+ hook(name: "build:before" | "close", callback: () => void | Promise<void>): void;
111
159
  };
112
160
  scannedHandlers: Array<{
113
161
  method?: string;
@@ -118,8 +166,13 @@ interface NitroRouteGuard {
118
166
  export declare function mergeGeneratedSourceNitroConfig(value: unknown, generatedHandlers: GeneratedSourceHandler[]): NitroGeneratedConfig;
119
167
  export declare function toRuntimeModuleSpecifier(file: string): string;
120
168
  export declare function toTypeModuleSpecifier(file: string): string;
169
+ /** Inspects the named Collection export without running application code. The docs snippet check calls it. */
170
+ export declare function inspectCollectionModule(file: string, source: string, exportName: string): {
171
+ exported: boolean;
172
+ routeEnabled: boolean;
173
+ };
121
174
  /**
122
- * Find the `server/content.{ts,js}` file that exports the application Content runtime as `content`. Returns undefined when
175
+ * Find the `server/content.{ts,js}` file whose default export is the application Content runtime. Returns undefined when
123
176
  * the project has none. The generated `/api/content/**` route and the Console content editor import the same file.
124
177
  */
125
178
  export declare function findContentEntry(options: Pick<SourceGenerationOptions, "projectRoot" | "serverDirs">): Promise<string | undefined>;
@@ -133,13 +186,27 @@ export interface ContentEntryFeatures {
133
186
  sitemap: boolean;
134
187
  /** `seo: { robots }` that is not literally false. */
135
188
  robots: boolean;
189
+ /** `seo: { markdown }` that is not literally false, or `seo: { llms }` on, whose links need the Markdown copies. */
190
+ markdown: boolean;
191
+ /** `seo: { rss }` that is not literally false. */
192
+ rss: boolean;
193
+ /** Whether `seo.mcp` is enabled, or unknown when discovery cannot follow its value. */
194
+ mcp: boolean | "unknown";
195
+ /** `seo: { llms }` that is not literally false. */
196
+ llms: boolean;
136
197
  /** `live` that is not literally false: Content edits Markdown documents live where Realtime has a room authority. */
137
198
  live: boolean;
199
+ /** `previews` that is set and not literally false: Content serves refs of its `github()` Source at `/tree`, `/blob`, and `/pr` URLs. */
200
+ previews: boolean;
201
+ /** The module imports `sqlite` from `vite-hub/content/sqlite`, so SQLite WASM must load when a Worker starts. */
202
+ sqlite: boolean;
203
+ /** The module imports `github` from `vite-hub/source`, so a push webhook route can move the head of its Sources. */
204
+ github: boolean;
138
205
  }
139
206
  /**
140
- * Read the `defineContent()` call that initializes the `content` export. Collections count as present unless the call
207
+ * Read the `defineContent()` call that the default export holds. Collections count as present unless the call
141
208
  * provably has no non-empty `collections` object. SEO routes count only when the call has a `seo` option: a literal
142
- * `sitemap` or `robots` that is not `false`, or a `seo` value that discovery cannot follow.
209
+ * `sitemap`, `robots`, `markdown`, `rss`, `mcp`, or `llms` that is not `false`, or a `seo` value that discovery cannot follow.
143
210
  */
144
211
  export declare function inspectContentModule(program: unknown, contentImportBase?: string): ContentEntryFeatures;
145
212
  /** Read what the Content module defines without running it. A file that does not parse counts as defining everything. */
@@ -150,11 +217,11 @@ export declare function hubSource(options?: SourceVitePluginOptions): Plugin & {
150
217
  /** The `server/content.ts` file found by the last preparation of `projectRoot` (default: the latest root). */
151
218
  getContentDefinition: (projectRoot?: string) => ContentDefinitionFile | undefined;
152
219
  onGeneratedHandlersChanged: (listener: GeneratedSourceHandlersListener, options?: GeneratedSourceHandlersListenerOptions) => () => void;
153
- prepareSources: (options: Omit<SourceGenerationOptions, "auth" | "contentImportBase" | "importBase">) => Promise<GeneratedSourceHandler[]>;
220
+ prepareSources: (options: Omit<SourceGenerationOptions, "appSeo" | "auth" | "contentImportBase" | "importBase">) => Promise<GeneratedSourceHandler[]>;
154
221
  };
155
222
  nitro: {
156
223
  name: string;
157
- setup(nitro: SourceNitroHost): void;
224
+ setup(nitro: SourceNitroHost): Promise<void>;
158
225
  };
159
226
  vitehub: ViteHubInspectionPluginMetadata;
160
227
  };