@vite-hub/source 0.0.4 → 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 (48) hide show
  1. package/README.md +219 -82
  2. package/dist/{auth-Ddw55OUG.js → auth-B-tX_rp0.js} +255 -90
  3. package/dist/{client-CDfTmtQu.js → client-BwstxtdY.js} +584 -207
  4. package/dist/client.d.ts +27 -10
  5. package/dist/client.js +71 -13
  6. package/dist/collection-B_4w_J8h.d.ts +257 -0
  7. package/dist/{collection-B8pXGM2d.js → collection-cursor-WzV1Jd6v.js} +37 -54
  8. package/dist/collection-route-BplWPxHR.js +10 -0
  9. package/dist/drizzle.d.ts +41 -0
  10. package/dist/drizzle.js +89 -0
  11. package/dist/error-diagnostics-X0kuFjBT.js +51 -0
  12. package/dist/file-BX0FSvgE.js +60 -0
  13. package/dist/{file-EQ3AjVM6.d.ts → file-DadN9dbN.d.ts} +2 -3
  14. package/dist/file.d.ts +1 -1
  15. package/dist/file.js +1 -1
  16. package/dist/files.d.ts +15 -0
  17. package/dist/files.js +38 -0
  18. package/dist/github.d.ts +8 -5
  19. package/dist/github.js +725 -426
  20. package/dist/glob-BmFqTvJY.js +993 -0
  21. package/dist/glob.d.ts +12 -4
  22. package/dist/glob.js +1 -894
  23. package/dist/index.d.ts +118 -27
  24. package/dist/index.js +623 -14
  25. package/dist/markdown.d.ts +4 -6
  26. package/dist/markdown.js +2 -2
  27. package/dist/mcp.d.ts +3 -4
  28. package/dist/mcp.js +302 -5920
  29. package/dist/{file-BSWQg9Qv.js → mrmime-40h5OOIp.js} +1 -56
  30. package/dist/{path-CUhvUREm.js → path-BS8rYm0n.js} +60 -40
  31. package/dist/{path-BzmU4Eni.js → path-DOBpV8ol.js} +3 -7
  32. package/dist/server.d.ts +256 -6
  33. package/dist/server.js +90 -12
  34. package/dist/{sse-CE9Q2JqM.js → sse-D9gqqNPj.js} +50 -9
  35. package/dist/{streamableHttp-BszaXLmg.js → streamableHttp-BL-E7pl5.js} +40 -22
  36. package/dist/types-BigOktIj.d.ts +93 -0
  37. package/dist/{types-AIBmt_m6.js → types-CoWcW8oz.js} +2502 -1187
  38. package/dist/vite.d.ts +134 -13
  39. package/dist/vite.js +1734 -79
  40. package/package.json +55 -36
  41. package/dist/collection-CF2ON__k.d.ts +0 -92
  42. package/dist/collection-route-Dw7QLFyx.js +0 -6
  43. package/dist/content/client.d.ts +0 -3
  44. package/dist/content/client.js +0 -2
  45. package/dist/content.d.ts +0 -44
  46. package/dist/content.js +0 -157
  47. package/dist/registry-C8skfCSV.js +0 -120
  48. package/dist/types-Bu3WvNX9.d.ts +0 -71
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @vite-hub/source
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Sources" src="https://img.shields.io/badge/Source-typed%20retrieval-0f766e?style=flat-square">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
+ <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
+ <img alt="Sources" src="https://comark-ui.onmax.me/badge.svg?label=Source&amp;value=typed+retrieval">
7
7
  </p>
8
8
 
9
9
  `@vite-hub/source` loads files, globs, markdown, GitHub content, or custom data before something else places it in a workspace.
@@ -14,132 +14,177 @@
14
14
  pnpm add @vite-hub/source
15
15
  ```
16
16
 
17
- ## Minimal API
17
+ ## Open a Source
18
18
 
19
19
  ```ts
20
- // server/utils/sources.ts
21
- import { defineSources, registerSources, useSource } from "@vite-hub/source"
22
- import { file } from "@vite-hub/source/file"
23
- import { github } from "@vite-hub/source/github"
20
+ import { createSource } from "@vite-hub/source"
24
21
  import { glob } from "@vite-hub/source/glob"
25
22
 
26
- registerSources(defineSources({
27
- docs: glob({ include: "docs/**/*.md" }),
28
- readme: file("README.md"),
29
- upstream: github({ repo: "vite-hub/vitehub" }),
30
- }))
23
+ export const docs = glob({ cwd: "docs", include: "**/*.md" })
31
24
 
32
- const docs = useSource("docs", { rootDir: process.cwd() })
33
- const revision = await docs.revision()
34
- const keys = await docs.keys()
35
- const first = await docs.read(keys[0]!)
25
+ const reader = createSource(docs, { rootDir: process.cwd() })
26
+ const revision = await reader.revision()
27
+ const keys = await reader.keys()
28
+ const first = await reader.read(keys[0]!)
36
29
  ```
37
30
 
38
- `revision()` resolves an origin snapshot once per reader. Revision-aware loaders
39
- then use the same immutable identity for preparation, keys, and item reads.
31
+ `createSource(definition, context?)` infers keys, items, and metadata from the
32
+ Source definition. It resolves a revision and prepares the Source once per
33
+ reader. Revision-aware loaders receive the same pinned revision on every
34
+ operation. Loaders without revision support can observe origin changes. Create
35
+ another reader to resolve a new revision. No registration or global type map is needed.
40
36
 
41
- ## Runtime content with Comark Content
37
+ `glob()` treats both `/` and `\` as path separators in `include` and `ignore`,
38
+ including before wildcards: the JavaScript string `"docs\\*.md"` means
39
+ `"docs/*.md"`. Backslashes never escape glob metacharacters. To match literal
40
+ characters, use bracket expressions: `[*]` for `*`, `[?]` for `?`, and `[[]`
41
+ for `[`. For example, `"docs/file[[]1].md"` matches `docs/file[1].md`.
42
+ The same normalized patterns are used for discovery and final filtering.
42
43
 
43
- Source owns origin retrieval. [Comark Content](https://docs-template.comark.dev/concepts/architecture)
44
- can own the derived content system: Markdown parsing, manifests, navigation,
45
- cache artifacts, runtime HTTP handling, SQL queries, and ranked full-text
46
- search. Adapt any registered ViteHub Source instead of recreating those
47
- features in its loader:
44
+ `glob()` keeps its cached key listing in each reader. Opening another reader
45
+ refreshes that reader's listing without changing existing readers. File content
46
+ and metadata are read from the current file system. Set `keyCache: false` to
47
+ refresh keys on each listing and when an item is missing from the latest listing.
48
48
 
49
- ```sh
50
- pnpm add @vite-hub/source comark-content
51
- ```
49
+ `file()` follows a symbolic link only when its resolved target stays inside the Source root. `glob()` is also confined to the Source root. It does not follow symbolic links by default, and it checks each file path again before it reads content or metadata. Set `followSymlinks: true` to follow links when their resolved targets stay inside the Source root. This option controls file selection. It does not isolate the process from concurrent file system changes.
50
+
51
+ File paths are relative to the Source root. Absolute paths, Windows drive paths such as `C:notes.md`, parent traversal, and null bytes are rejected on every host.
52
+
53
+ Use `defineSource()` for custom loaders:
52
54
 
53
55
  ```ts
54
- import sqlite from "comark-content/database/sqlite-node"
55
- import sqliteFullTextSearch from "comark-content/plugins/sqlite-full-text-search"
56
- import { defineContent } from "@vite-hub/source/content"
56
+ import { createSource, defineSource } from "@vite-hub/source"
57
57
 
58
- export const content = defineContent({
59
- plugins: [sqliteFullTextSearch({ database: sqlite() })],
60
- sources: {
61
- docs: "docs",
58
+ const articles = defineSource({
59
+ name: "articles",
60
+ async getKeys() {
61
+ return ["article_123" as const]
62
+ },
63
+ async getItem(key: `article_${string}`) {
64
+ return { key, data: { title: "Source API" }, metadata: { version: 1 } }
62
65
  },
63
66
  })
64
67
 
65
- await content.get("/guide")
66
- await content.navigation(["docs"])
67
- await content.search(["docs"], "runtime")
68
+ const article = await createSource(articles).get("article_123")
69
+ article.data.title
70
+ article.metadata.version
71
+ ```
72
+
73
+ Every loader has `name`, `getKeys()`, and `getItem()`. Optional hooks include
74
+ `resolveRevision()`, `prepare()`, `getItems()`, and `getMeta()`.
75
+ `SourceReader<typeof articles>`, `SourceKey<typeof articles>`,
76
+ `SourceData<typeof articles>`, and `SourceMetadata<typeof articles>` use the
77
+ definition type.
78
+
79
+ All managed readers expose `revision()`, `keys()`, `get()`, `items()`, `meta()`,
80
+ and `exists()`. File readers also expose `read()` and `list()`. Built-in `file`,
81
+ `glob`, `github`, `markdown`, and `mcpResources` loaders return `FileSource`.
82
+ Their `SourceFile` items guarantee `content`. Custom loaders that guarantee
83
+ content receive file methods too. Record readers use `get()` and `items()`.
84
+
85
+ `github()` reads GitHub through `@vite-hub/forge`. `auth` is a token or a trusted
86
+ callback. Without `auth`, it reads Server Env `VITEHUB_GITHUB_TOKEN`, then
87
+ `FORGES_GITHUB_TOKEN`. It does not read `GH_TOKEN` or `GITHUB_TOKEN`.
88
+ `auth: false` reads without a token.
68
89
 
90
+ `glob()` takes a pattern or options. In a pattern, the folders before the first
91
+ wildcard are `cwd`, so keys are the paths below them:
92
+
93
+ ```ts
94
+ import { glob } from "@vite-hub/source/glob"
95
+
96
+ export const docs = glob("content/docs/**/*.md") // keys like "guide/setup.md"
69
97
  ```
70
98
 
71
- With ViteHub's Vite or Nuxt integration, `server/content.ts` is discovered and
72
- served at `/api/content/**`; no framework route is required. `defineContent()`
73
- returns the Comark Content instance, including methods contributed by its query,
74
- search, references, and custom plugins. Each Comark cache refresh gets a new
75
- ViteHub Source Reader and origin revision, while every individual load remains
76
- pinned to one revision.
99
+ Under `vite dev` it reads the files from disk. A server build with `hubSource()`
100
+ bundles the files of a call whose options are literals, through `files()`, so
101
+ hosts without a runtime file system, such as Cloudflare Workers, serve them.
102
+ `files(entries, { base, prefix })` serves files the server already holds.
77
103
 
78
- Use `sqlite-wasm` instead of `sqlite-node` on runtimes without Node's SQLite
79
- module. Comark's cache accepts an unstorage driver and exposes
80
- `refresh(source)`, `invalidate(key)`, and `expire(key)`, so applications do not
81
- need a second parsed-content cache in ViteHub.
104
+ ## Reuse a definition
82
105
 
83
- Use Comark's native Sources directly when ViteHub retrieval is unnecessary:
106
+ Content accepts Source definitions directly. It opens a new reader on each
107
+ refresh, so overlapping loads keep separate revisions:
84
108
 
85
109
  ```ts
86
- import fs from "comark-content/sources/fs"
87
- import { defineContent } from "@vite-hub/source/content"
110
+ import { defineContent } from "@vite-hub/content"
111
+
112
+ export const content = defineContent({ source: docs })
113
+ ```
114
+
115
+ Workspace binds the same definition to a persistent file tree:
88
116
 
89
- export const content = defineContent({
117
+ ```ts
118
+ import { defineWorkspace } from "@vite-hub/workspace"
119
+
120
+ export default defineWorkspace({
90
121
  sources: {
91
- assets: fs(".data/assets", { prefix: "public" }),
122
+ docs: { source: docs, mount: "docs", materialize: "lazy" },
92
123
  },
93
124
  })
94
125
  ```
95
126
 
96
- On the client, use `createContentClient` from
97
- `@vite-hub/source/content/client`. Add Comark's SQL-query or full-text-search
98
- client plugin to call the same plugin methods over the generated endpoint.
99
-
100
- Workspace search remains filesystem search over the visible Workspace tree.
101
- Comark search is semantic content search over parsed documents. They deliberately
102
- have different owners and result contracts.
127
+ Workspace owns paths, materialization, sync, and access rules. Source owns
128
+ retrieval. Content owns parsed documents, navigation, queries, and search.
103
129
 
104
- Structured sources preserve record and metadata types through `useSource()`:
130
+ ## Optional name lookup
105
131
 
106
132
  ```ts
107
- import type { Source } from "@vite-hub/source"
108
-
109
- interface Article {
110
- author: string
111
- cover: { key: string, mediaType: string }
112
- title: string
113
- }
133
+ import { defineSources, registerSources, useSource } from "@vite-hub/source"
114
134
 
115
- interface ArticleMetadata {
116
- revision: string
117
- }
135
+ const sources = defineSources({ docs })
136
+ registerSources(sources)
118
137
 
119
138
  declare global {
120
139
  interface ViteHubSourceMap {
121
- articles: Source<`article_${string}`, Article, ArticleMetadata>
140
+ docs: typeof docs
122
141
  }
123
142
  }
124
143
 
125
- const article = await useSource("articles").get("article_123")
126
- article.data?.title
127
- article.metadata?.revision
144
+ await useSource("docs").read("intro.md")
145
+ ```
146
+
147
+ `useSource(name, context?)` opens the same managed reader through a process-local
148
+ registry. Import the registration module before lookup. The Vite integration
149
+ for Collections and Content does not generate `ViteHubSourceMap`.
150
+ `RegisteredSource<"docs">` resolves a registered name to its definition type.
128
151
 
129
- const articles = await useSource("articles").items()
152
+ ## Split items into parts
153
+
154
+ `splitSource()` turns each item of a Source into several items, such as the
155
+ sections of a Markdown file. Each part key is `<parent key>#<part key>`:
156
+
157
+ ```ts
158
+ import { createSource, splitSource } from "@vite-hub/source"
159
+ import { glob } from "@vite-hub/source/glob"
160
+
161
+ const sections = splitSource({
162
+ source: glob({ cwd: "docs", include: "**/*.md" }),
163
+ split: file => String(file.content).split(/^## /m).slice(1)
164
+ .map(section => ({ key: section.slice(0, section.indexOf("\n")), content: section })),
165
+ })
166
+
167
+ await createSource(sections).read("guide.md#Usage")
130
168
  ```
131
169
 
132
- Combine runtime Source readers when keys can overlap:
170
+ The result is a Source definition. `get()` reads only the parent item of the
171
+ part, and a part without a `path` keeps the parent's path. Part keys must be
172
+ unique in their parent item and must not contain `#`.
173
+
174
+ ## Combine keyed readers
175
+
176
+ Use ordinary objects or functions for readers that do not need a loader
177
+ lifecycle. `combineSources()` keeps aliases in each key and result:
133
178
 
134
179
  ```ts
135
- import { combineSources, defineSource } from "@vite-hub/source"
180
+ import { combineSources } from "@vite-hub/source"
136
181
 
137
182
  const recaps = combineSources({
138
183
  sources: {
139
- github: defineSource({
184
+ github: {
140
185
  get: async (month: `${number}-${number}`) => ({ month }),
141
186
  items: async () => [{ key: "2026-07" as const }],
142
- }),
187
+ },
143
188
  },
144
189
  })
145
190
 
@@ -147,6 +192,23 @@ await recaps.get(["github", "2026-07"])
147
192
  await recaps.items() // [{ key: "2026-07", source: "github", identity: ["github", "2026-07"] }]
148
193
  ```
149
194
 
195
+ A combined reader exposes `items()` only when every input implements it.
196
+
197
+ Use `cachedSource()` to add Nitro caching to a keyed reader. It loads
198
+ `nitro/cache` on the first `get()`, so the app must run on Nitro:
199
+
200
+ ```ts
201
+ import { cachedSource } from "@vite-hub/source/server"
202
+
203
+ const cachedDocs = cachedSource(createSource(docs), { name: "docs", maxAge: 60 })
204
+ await cachedDocs.get("intro.md")
205
+ ```
206
+
207
+ Use a different cache name for each origin and access scope. Cache ordinary
208
+ readers before passing them to `combineSources()`.
209
+
210
+ ## Collections
211
+
150
212
  Define a Collection when a database or other origin should become a typed,
151
213
  paginated client read model:
152
214
 
@@ -167,6 +229,8 @@ export const articles = defineCollection(async ({ cursor, limit, query }) => {
167
229
 
168
230
  `cursorSchema` and `querySchema` accept any Standard Schema validator. Their
169
231
  output types flow into the loader, so the loader needs no manual generic types.
232
+ The Collection exposes `querySchema` so tools such as `vitehub channels replay`
233
+ can describe the accepted query keys.
170
234
 
171
235
  ```ts
172
236
  // app/composables/articles.ts
@@ -181,8 +245,16 @@ export const useArticles = () => useCollection("articles", {
181
245
  ViteHub discovers modules in `server/collections` and generates the collection
182
246
  registry and GET handler. The module must export a Collection with the same name
183
247
  as its filename, so `articles.ts` exports `articles` and maps to `/api/articles`.
184
- Everything in that directory is a public read model; keep private definitions
185
- elsewhere and do not repeat the route under `server/api`. Restart Nuxt after
248
+ A Collection is a public read model unless it sets `authorize`. `authorize: true`
249
+ requires a signed-in `@vite-hub/auth` session, and a callback receives
250
+ `{ request, session, user }` and returns `true`, `false` for `403`, or a
251
+ `Response`. The route checks access before it parses the query. Without a session
252
+ it returns `401`, and `useCollection()` sets `error` to a `CollectionAccessError`
253
+ with that `status`. Generated routes wrap the page with Auth's `withAuthorization` when the host
254
+ enables Auth with a discovered Auth Definition (`hubSource({ auth: true })`
255
+ alongside `hubAuth()` outside `vite-hub`); otherwise a
256
+ Collection with `authorize` fails closed. Do not repeat the route under
257
+ `server/api`. Restart Nuxt after
186
258
  adding, removing, or renaming a Collection module so Nitro rebuilds its handler
187
259
  manifest.
188
260
  Callers do not repeat URL strings or generic imports. `filter` is validated by
@@ -193,10 +265,75 @@ origin-specific query. Collection owns limit enforcement, opaque cursor
193
265
  transport, response shaping, and the exact item and filter types consumed by
194
266
  `useCollection()`.
195
267
 
268
+ ### Collections over an array
269
+
270
+ When the whole data set fits in memory, pass `array()` as the Collection source.
271
+ It filters, searches, sorts, counts, and pages the array, and returns `total` and
272
+ `facets` with each page:
273
+
274
+ ```ts
275
+ // server/collections/articles.ts
276
+ import { array, defineCollection } from "@vite-hub/source"
277
+
278
+ export const articles = defineCollection({
279
+ source: array(() => loadArticles(), {
280
+ facets: ["category"],
281
+ filters: ["category", "authors.name"],
282
+ key: "slug",
283
+ search: ["title", "summary"],
284
+ sort: { field: "title" },
285
+ }),
286
+ transform: article => ({ slug: article.slug, title: article.title }),
287
+ })
288
+ ```
289
+
290
+ Clients filter with the declared field paths: `?category=guide` matches without
291
+ case, a repeated key matches any of its values, `?empty=category` matches items
292
+ with no value, and `?search=` matches the `search` fields. Any other key returns
293
+ `400`. Cursors are bound to the data and the query. A cursor from changed data or
294
+ another query returns `409`. `load` runs on every request; return
295
+ `{ items, digest }` when the origin already has a content digest, or ViteHub
296
+ hashes the items for pagination. Keyed lookups do not compute a digest.
297
+ `useCollection()` exposes `total` and `facets` from the latest
298
+ page. `key` adds `collection.get(key)` for server code, and `schema` validates
299
+ every item and types it from the schema output. Use a database `table()`
300
+ from `@vite-hub/source/drizzle` when the data set should not be loaded per
301
+ request. `table()` needs the optional `drizzle-orm` peer. `vite-hub/source`
302
+ exports `table()` too.
303
+
304
+ `workspaceFile()` from `@vite-hub/workspace` is the same source over a JSON array
305
+ in a Workspace file.
306
+
307
+ Pass `{ signal }` to `collection.get(key, { signal })` to cancel a direct read.
308
+ Cancelled reads reject with the signal's reason, including when a loader or
309
+ transform returns after cancellation.
310
+
196
311
  Keep binary assets behind the Blob boundary and store a serializable reference in
197
312
  the record. This keeps ordinary record reads lazy while treating the structured
198
313
  data and its assets as one logical item.
199
314
 
315
+ ### Inspect Collections
316
+
317
+ `vitehub inspect definitions --kind collection` lists each discovered Collection
318
+ with its file, source kind, and the options that it sets: schema, key, sort,
319
+ filters, search, facets, limits, transform, authorize, and route. The
320
+ `hubSource()` plugin contributes this list through `vitehub.inspect`, and
321
+ `inspectCollectionDefinitions({ projectRoot, serverDirs })` from
322
+ `@vite-hub/source/vite` returns the same summaries. Inspection reads the module
323
+ text and does not run it, so a value that is computed at runtime shows as
324
+ `Dynamic`.
325
+
326
+ ```txt
327
+ Collections (collection): 1
328
+ articles server/collections/articles.ts [server-collections]
329
+ Source: array
330
+ Key: slug
331
+ Sort: publishedAt desc
332
+ Filters: category, authors.name
333
+ Transform: Yes
334
+ Route: GET /api/articles
335
+ ```
336
+
200
337
  ## Used by
201
338
 
202
339
  [`@vite-hub/workspace`](../workspace/README.md) materializes Source output into workspace files. Use this package directly when you only need typed source loading and not a workspace file tree.