@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/dist/index.js CHANGED
@@ -1,39 +1,653 @@
1
- import { a as sourceError } from "./path-BzmU4Eni.js";
2
- import { a as useSource, i as registerSources, n as getRegisteredSource, r as registerSource, t as clearSources } from "./registry-C8skfCSV.js";
3
- import { n as defineCollection, t as CollectionCursorError } from "./collection-B8pXGM2d.js";
1
+ import { t as sourceErrorDiagnostics } from "./error-diagnostics-X0kuFjBT.js";
2
+ import { n as createCollectionCursorCodec, r as parseCollectionSchema, t as CollectionCursorError } from "./collection-cursor-WzV1Jd6v.js";
3
+ import { a as sourceNotFoundError, i as sourceError, n as normalizeSafeSourcePath, r as normalizeSourcePath, t as decodeSourceContent } from "./path-DOBpV8ol.js";
4
+ //#region src/core/array-collection.ts
5
+ const defaultMaxLimit$1 = 100;
6
+ const reservedQueryKeys = /* @__PURE__ */ new Set([
7
+ "cursor",
8
+ "empty",
9
+ "limit",
10
+ "search"
11
+ ]);
12
+ function compareProtocolStrings(left, right) {
13
+ return left < right ? -1 : left > right ? 1 : 0;
14
+ }
15
+ const cursorCodec = createCollectionCursorCodec({ "~standard": {
16
+ version: 1,
17
+ vendor: "vite-hub",
18
+ validate(value) {
19
+ const cursor = Object(value);
20
+ const digest = Reflect.get(cursor, "digest");
21
+ const offset = Reflect.get(cursor, "offset");
22
+ const query = Reflect.get(cursor, "query");
23
+ if (Object(value) !== value || String(digest) !== digest || String(query) !== query || !Number.isSafeInteger(offset) || Number(offset) < 0 || Reflect.ownKeys(cursor).length !== 3) return { issues: [{ message: "Array Collection cursor is malformed." }] };
24
+ return { value: {
25
+ digest: String(digest),
26
+ offset: Number(offset),
27
+ query: String(query)
28
+ } };
29
+ }
30
+ } });
31
+ function isRecord(value) {
32
+ return Object(value) === value && !Array.isArray(value);
33
+ }
34
+ /** Read a dot path through own properties. Arrays fan out to every element. */
35
+ function collectionValueAt(value, path) {
36
+ const segments = path.split(".").filter(Boolean);
37
+ function visit(current, remaining) {
38
+ if (!remaining.length) return current;
39
+ if (Array.isArray(current)) return current.map((item) => visit(item, remaining)).filter((item) => item !== void 0);
40
+ if (!isRecord(current)) return;
41
+ const segment = remaining[0];
42
+ if (!Object.hasOwn(current, segment)) return;
43
+ return visit(current[segment], remaining.slice(1));
44
+ }
45
+ return visit(value, segments);
46
+ }
47
+ function dateTime(value) {
48
+ if (Object.prototype.toString.call(value) !== "[object Date]") return;
49
+ const time = Date.prototype.getTime.call(value);
50
+ return Number.isNaN(time) ? void 0 : time;
51
+ }
52
+ function scalarValues(value) {
53
+ if (Array.isArray(value)) return value.flatMap(scalarValues);
54
+ const time = dateTime(value);
55
+ if (time !== void 0) return [new Date(time).toISOString()];
56
+ if (value === null || value === void 0 || Object(value) === value) return [];
57
+ return [String(value)];
58
+ }
59
+ function firstScalar(value) {
60
+ const entry = Array.isArray(value) ? value.flat(Infinity).find((item) => item !== null && item !== void 0 && (Object(item) !== item || dateTime(item) !== void 0)) : value;
61
+ return dateTime(entry) ?? entry;
62
+ }
63
+ function isString(value) {
64
+ return String(value) === value;
65
+ }
66
+ function stringList(value) {
67
+ return (Array.isArray(value) ? value : [value]).filter((entry) => String(entry) === entry);
68
+ }
69
+ async function sha256(value) {
70
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
71
+ return [...new Uint8Array(hash)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
+ }
73
+ function assertFieldList(label, fields) {
74
+ if (fields === void 0) return;
75
+ if (!Array.isArray(fields) || fields.some((field) => String(field) !== field || !field)) throw sourceErrorDiagnostics.SOURCE_R0028({ message: `[vitehub] array() ${label} must be a list of field paths.` });
76
+ }
77
+ function normalizeQuery(query) {
78
+ const normalized = {
79
+ empty: [],
80
+ filters: Object.create(null),
81
+ search: ""
82
+ };
83
+ for (const [key, value] of Object.entries(query).sort(([a], [b]) => compareProtocolStrings(a, b))) {
84
+ if (value === void 0 || value === null) continue;
85
+ if (key === "search") {
86
+ normalized.search = String(value).trim().toLocaleLowerCase();
87
+ continue;
88
+ }
89
+ if (key === "empty") {
90
+ normalized.empty = [...new Set(stringList(value))].sort();
91
+ continue;
92
+ }
93
+ const values = stringList(value).map((entry) => entry.toLocaleLowerCase());
94
+ if (values.length) normalized.filters[key] = [...new Set(values)].sort();
95
+ }
96
+ return normalized;
97
+ }
98
+ function matches(item, query, searchFields) {
99
+ for (const [field, expected] of Object.entries(query.filters)) {
100
+ const values = scalarValues(collectionValueAt(item, field)).map((value) => value.toLocaleLowerCase());
101
+ if (!expected.some((candidate) => values.includes(candidate))) return false;
102
+ }
103
+ for (const field of query.empty) if (scalarValues(collectionValueAt(item, field)).length) return false;
104
+ if (query.search) return searchFields.some((field) => scalarValues(collectionValueAt(item, field)).some((value) => value.toLocaleLowerCase().includes(query.search)));
105
+ return true;
106
+ }
107
+ function sortItems(items, sort) {
108
+ if (!sort) return items;
109
+ const direction = sort.direction === "desc" ? -1 : 1;
110
+ return items.map((item) => ({
111
+ item,
112
+ value: firstScalar(collectionValueAt(item, sort.field))
113
+ })).sort(({ value: leftValue }, { value: rightValue }) => {
114
+ if (Number(leftValue) === leftValue && Number(rightValue) === rightValue) return (leftValue - rightValue) * direction;
115
+ return String(leftValue ?? "").localeCompare(String(rightValue ?? "")) * direction;
116
+ }).map(({ item }) => item);
117
+ }
118
+ function buildFacets(items, fields, maxValues) {
119
+ return Object.fromEntries(fields.map((field) => {
120
+ const counts = /* @__PURE__ */ new Map();
121
+ for (const item of items) for (const value of new Set(scalarValues(collectionValueAt(item, field)))) counts.set(value, (counts.get(value) ?? 0) + 1);
122
+ return [field, [...counts].map(([value, count]) => ({
123
+ count,
124
+ value
125
+ })).sort((left, right) => right.count - left.count || left.value.localeCompare(right.value)).slice(0, maxValues)];
126
+ }));
127
+ }
128
+ function array(load, options = {}) {
129
+ assertFieldList("filters", options.filters);
130
+ assertFieldList("search", options.search);
131
+ assertFieldList("facets", options.facets);
132
+ const reserved = options.filters?.find((field) => reservedQueryKeys.has(field));
133
+ if (reserved) throw sourceErrorDiagnostics.SOURCE_R0028({ message: `[vitehub] array() filter ${JSON.stringify(reserved)} collides with a reserved query key.` });
134
+ if (options.sort !== void 0 && (!isRecord(options.sort) || String(options.sort.field) !== options.sort.field || !options.sort.field)) throw sourceErrorDiagnostics.SOURCE_R0028({ message: "[vitehub] array() sort must name a field." });
135
+ const filters = new Set(options.filters ?? []);
136
+ const isFilter = (key) => filters.has(key);
137
+ const searchFields = options.search ?? [];
138
+ const facetFields = options.facets ?? [];
139
+ const maxValues = options.maxLimit ?? defaultMaxLimit$1;
140
+ const signatureFields = JSON.stringify({
141
+ search: [...searchFields].sort(),
142
+ sort: options.sort ? {
143
+ direction: options.sort.direction ?? "asc",
144
+ field: options.sort.field
145
+ } : null
146
+ });
147
+ async function snapshot(signal, includeDigest) {
148
+ const result = typeof load === "function" ? await load({ signal }) : load;
149
+ signal?.throwIfAborted();
150
+ const items = Array.isArray(result) ? result : Reflect.get(Object(result), "items");
151
+ if (!Array.isArray(items)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] array() load must return an array or { items, digest }." });
152
+ const digest = Array.isArray(result) ? void 0 : Reflect.get(Object(result), "digest");
153
+ if (digest !== void 0 && (String(digest) !== digest || !digest)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] array() digest must be a non-empty string." });
154
+ const contentDigest = includeDigest ? String(digest ?? await sha256(JSON.stringify(items))) : "";
155
+ const schema = options.schema;
156
+ if (schema) return {
157
+ digest: contentDigest,
158
+ items: await Promise.all(items.map(async (item, index) => {
159
+ try {
160
+ return await parseCollectionSchema(schema, item);
161
+ } catch (cause) {
162
+ throw sourceErrorDiagnostics.SOURCE_R0006({
163
+ cause,
164
+ message: `[vitehub] array() item ${index} does not match its schema: ${cause instanceof Error ? cause.message : String(cause)}`
165
+ });
166
+ }
167
+ }))
168
+ };
169
+ return {
170
+ digest: contentDigest,
171
+ items
172
+ };
173
+ }
174
+ const source = {
175
+ defaultLimit: options.defaultLimit,
176
+ maxLimit: options.maxLimit,
177
+ pagination: "provider",
178
+ querySchema: { "~standard": {
179
+ version: 1,
180
+ vendor: "vite-hub",
181
+ validate(value) {
182
+ if (!isRecord(value)) return { issues: [{ message: "Collection query must be an object." }] };
183
+ const filterValues = Object.create(null);
184
+ let empty;
185
+ let search;
186
+ for (const [key, raw] of Object.entries(value)) {
187
+ if (raw === void 0 || raw === null) continue;
188
+ const values = Array.isArray(raw) ? raw : [raw];
189
+ if (!values.every(isString)) return { issues: [{ message: `Collection query ${JSON.stringify(key)} must be a string.` }] };
190
+ if (key === "search") {
191
+ if (values.length !== 1) return { issues: [{ message: "Collection search must have one value." }] };
192
+ if (values[0] && !searchFields.length) return { issues: [{ message: "Collection search is not enabled." }] };
193
+ search = values[0];
194
+ continue;
195
+ }
196
+ if (key === "empty") {
197
+ const unknown = values.find((field) => !isFilter(field));
198
+ if (unknown !== void 0) return { issues: [{ message: `Collection filter ${JSON.stringify(unknown)} is not allowed.` }] };
199
+ empty = values.filter(isFilter);
200
+ continue;
201
+ }
202
+ if (!isFilter(key)) return { issues: [{ message: `Collection query parameter ${JSON.stringify(key)} is not allowed.` }] };
203
+ filterValues[key] = values.map((entry) => entry.trim());
204
+ }
205
+ const parsed = { ...filterValues };
206
+ if (empty) parsed.empty = empty;
207
+ if (search !== void 0) parsed.search = search;
208
+ return { value: parsed };
209
+ }
210
+ } },
211
+ async load({ cursor, limit, query, signal }) {
212
+ const { digest, items } = await snapshot(signal, true);
213
+ const normalized = normalizeQuery(query);
214
+ const matching = sortItems(items.filter((item) => matches(item, normalized, searchFields)), options.sort);
215
+ const signature = await sha256(`${signatureFields}\n${JSON.stringify(normalized)}`);
216
+ const decoded = await cursorCodec.decode(cursor);
217
+ if (decoded && (decoded.digest !== digest || decoded.query !== signature)) throw new CollectionCursorError(void 0, { reason: "stale" });
218
+ const offset = decoded?.offset ?? 0;
219
+ if (offset > matching.length) throw new CollectionCursorError();
220
+ const pageItems = matching.slice(offset, offset + limit);
221
+ const nextOffset = offset + pageItems.length;
222
+ const page = {
223
+ items: pageItems,
224
+ nextCursor: nextOffset < matching.length ? cursorCodec.encode({
225
+ digest,
226
+ offset: nextOffset,
227
+ query: signature
228
+ }) : null,
229
+ total: matching.length
230
+ };
231
+ if (facetFields.length) page.facets = buildFacets(matching, facetFields, maxValues);
232
+ return page;
233
+ }
234
+ };
235
+ const key = options.key;
236
+ if (key !== void 0) {
237
+ if (String(key) !== key || !key) throw sourceErrorDiagnostics.SOURCE_R0028({ message: "[vitehub] array() key must be a field path." });
238
+ source.get = async (value, { signal }) => {
239
+ const { items } = await snapshot(signal, false);
240
+ return items.find((item) => scalarValues(collectionValueAt(item, key)).includes(value)) ?? null;
241
+ };
242
+ }
243
+ return source;
244
+ }
245
+ //#endregion
246
+ //#region src/core/collection.ts
247
+ const defaultPageLimit = 50;
248
+ const defaultMaxLimit = 100;
249
+ function isCollectionFacets(value) {
250
+ return Object(value) === value && !Array.isArray(value) && Object.values(Object(value)).every((entries) => Array.isArray(entries) && entries.every((entry) => Object(entry) === entry && String(Reflect.get(entry, "value")) === Reflect.get(entry, "value") && Number.isSafeInteger(Reflect.get(entry, "count")) && Number(Reflect.get(entry, "count")) >= 0));
251
+ }
252
+ function assertPositiveInteger(value, label) {
253
+ if (!Number.isSafeInteger(value) || value < 1) throw sourceErrorDiagnostics.SOURCE_R0004({ message: `[vitehub] Collection ${label} must be a positive integer.` });
254
+ }
255
+ function resolveLimit(limit, defaultLimit, maxLimit) {
256
+ if (limit !== void 0) assertPositiveInteger(limit, "limit");
257
+ return Math.min(limit ?? defaultLimit, maxLimit);
258
+ }
259
+ function defineCollection(input, options) {
260
+ const [load, definition] = typeof input === "function" ? [input, options] : sourceDefinition(input);
261
+ if (!definition) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] defineCollection() requires a loader with options, or { source }." });
262
+ const defaultLimit = definition.defaultLimit ?? defaultPageLimit;
263
+ const maxLimit = definition.maxLimit ?? defaultMaxLimit;
264
+ assertPositiveInteger(defaultLimit, "defaultLimit");
265
+ assertPositiveInteger(maxLimit, "maxLimit");
266
+ if (defaultLimit > maxLimit) throw sourceErrorDiagnostics.SOURCE_R0008({ message: "[vitehub] Collection defaultLimit cannot exceed maxLimit." });
267
+ const cursorDefinition = "cursorSchema" in definition ? definition : void 0;
268
+ const cursorCodec = cursorDefinition ? createCollectionCursorCodec(cursorDefinition.cursorSchema) : void 0;
269
+ const authorize = definition.authorize;
270
+ if (authorize !== void 0 && authorize !== true && typeof authorize !== "function") throw sourceErrorDiagnostics.SOURCE_R0024({ message: "[vitehub] Collection authorize must be true or a function." });
271
+ const collection = {
272
+ ...authorize ? { authorize } : {},
273
+ route: definition.route,
274
+ async page(request) {
275
+ request.signal?.throwIfAborted();
276
+ const limit = resolveLimit(request.limit, defaultLimit, maxLimit);
277
+ if (!cursorDefinition || !cursorCodec) {
278
+ const result = await load({
279
+ cursor: request.cursor,
280
+ limit,
281
+ query: request.query,
282
+ signal: request.signal
283
+ });
284
+ request.signal?.throwIfAborted();
285
+ if (!result || !Array.isArray(result.items) || result.nextCursor !== null && !isProviderCursor(result.nextCursor)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Provider Collection load() must return items and nextCursor." });
286
+ const transformedItems = definition.transform ? await Promise.all(result.items.map(definition.transform)) : result.items;
287
+ request.signal?.throwIfAborted();
288
+ const page = {
289
+ items: transformedItems,
290
+ nextCursor: result.nextCursor
291
+ };
292
+ if (result.total !== void 0) {
293
+ if (!Number.isSafeInteger(result.total) || result.total < 0) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Provider Collection total must be a non-negative integer." });
294
+ page.total = result.total;
295
+ }
296
+ if (result.facets !== void 0) {
297
+ if (!isCollectionFacets(result.facets)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Provider Collection facets must map fields to { value, count } lists." });
298
+ page.facets = result.facets;
299
+ }
300
+ return page;
301
+ }
302
+ const decodedCursor = await cursorCodec.decode(request.cursor);
303
+ request.signal?.throwIfAborted();
304
+ const sourceItems = await load({
305
+ cursor: decodedCursor,
306
+ limit: limit + 1,
307
+ query: request.query,
308
+ signal: request.signal
309
+ });
310
+ request.signal?.throwIfAborted();
311
+ if (!Array.isArray(sourceItems)) throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] Collection load() must return an array." });
312
+ const hasMore = sourceItems.length > limit;
313
+ const pageItems = sourceItems.slice(0, limit);
314
+ const nextCursor = hasMore && pageItems.length ? cursorCodec.encode(cursorDefinition.cursor(pageItems[pageItems.length - 1])) : null;
315
+ const transformedItems = definition.transform ? await Promise.all(pageItems.map(definition.transform)) : pageItems;
316
+ request.signal?.throwIfAborted();
317
+ return {
318
+ items: transformedItems,
319
+ nextCursor
320
+ };
321
+ },
322
+ async parseQuery(input) {
323
+ if (definition.querySchema) return await parseCollectionSchema(definition.querySchema, input);
324
+ return input;
325
+ },
326
+ query(input = {}) {
327
+ const project = (item, keys) => keys ? Object.fromEntries(keys.map((key) => [key, item[key]])) : item;
328
+ const build = (keys) => ({
329
+ select(...selected) {
330
+ return build(selected);
331
+ },
332
+ async page(options = {}) {
333
+ options.signal?.throwIfAborted();
334
+ const query = await collection.parseQuery(input);
335
+ const result = await collection.page({
336
+ ...options,
337
+ query
338
+ });
339
+ return {
340
+ ...result,
341
+ items: result.items.map((item) => project(item, keys))
342
+ };
343
+ },
344
+ async all(options = {}) {
345
+ options.signal?.throwIfAborted();
346
+ const items = [];
347
+ const query = await collection.parseQuery(input);
348
+ let cursor;
349
+ const seen = /* @__PURE__ */ new Set();
350
+ do {
351
+ options.signal?.throwIfAborted();
352
+ const result = await collection.page({
353
+ ...options,
354
+ cursor,
355
+ query
356
+ });
357
+ for (const item of result.items) items.push(project(item, keys));
358
+ cursor = result.nextCursor ?? void 0;
359
+ if (cursor !== void 0) {
360
+ if (seen.has(cursor)) throw new CollectionCursorError("[vitehub] Collection loader repeated a pagination cursor.");
361
+ seen.add(cursor);
362
+ }
363
+ } while (cursor !== void 0);
364
+ return items;
365
+ }
366
+ });
367
+ return build();
368
+ },
369
+ async all(options = {}) {
370
+ return collection.query(options.query).all(options);
371
+ },
372
+ ...definition.querySchema ? { querySchema: definition.querySchema } : {}
373
+ };
374
+ const get = definition.get;
375
+ if (get) {
376
+ const lookup = async (key, options) => {
377
+ options?.signal?.throwIfAborted();
378
+ const item = await get(key, options ?? {});
379
+ options?.signal?.throwIfAborted();
380
+ if (item === null || item === void 0) return item;
381
+ const result = definition.transform ? await definition.transform(item) : item;
382
+ options?.signal?.throwIfAborted();
383
+ return result;
384
+ };
385
+ Object.assign(collection, { get: lookup });
386
+ }
387
+ return collection;
388
+ }
389
+ function sourceDefinition(input) {
390
+ const { authorize, route, source, transform } = input;
391
+ if (Object(source) !== source || typeof source.load !== "function") throw sourceErrorDiagnostics.SOURCE_R0009({ message: "[vitehub] defineCollection({ source }) requires a Collection source with load()." });
392
+ const shared = {
393
+ authorize,
394
+ route,
395
+ get: source.get,
396
+ defaultLimit: source.defaultLimit,
397
+ maxLimit: source.maxLimit,
398
+ querySchema: source.querySchema,
399
+ transform
400
+ };
401
+ return source.pagination === "provider" ? [source.load, {
402
+ ...shared,
403
+ pagination: "provider"
404
+ }] : [source.load, {
405
+ ...shared,
406
+ cursor: source.cursor,
407
+ cursorSchema: source.cursorSchema
408
+ }];
409
+ }
410
+ function isProviderCursor(value) {
411
+ return value === String(value);
412
+ }
413
+ //#endregion
4
414
  //#region src/core/combine-sources.ts
5
415
  function combineSources(definition) {
6
416
  const sources = definition.sources;
7
417
  async function get(identity) {
8
- if (!Array.isArray(identity) || identity.length !== 2 || String(identity[0]) !== identity[0] || String(identity[1]) !== identity[1]) throw new TypeError("[vitehub] Combined Source identity must be a [source, key] string tuple.");
418
+ if (!Array.isArray(identity) || identity.length !== 2 || String(identity[0]) !== identity[0] || String(identity[1]) !== identity[1]) throw sourceErrorDiagnostics.SOURCE_R0010({ message: "[vitehub] Combined Source identity must be a [source, key] string tuple." });
9
419
  const [source, key] = identity;
10
420
  if (!Object.hasOwn(sources, source)) throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not defined.`);
11
421
  return await sources[source].get(key);
12
422
  }
13
423
  async function items() {
14
424
  const entries = Object.entries(sources);
15
- for (const [source, reader] of entries) if (!(reader.items instanceof Function)) throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not enumerable.`);
425
+ for (const [source, reader] of entries) if (typeof reader.items !== "function") throw sourceError(`[vitehub] Combined Source alias ${JSON.stringify(source)} is not enumerable.`);
16
426
  return (await Promise.all(entries.map(async ([source, reader]) => (await reader.items()).map((item) => ({
17
427
  ...item,
18
428
  identity: [source, item.key],
19
429
  source
20
430
  }))))).flat();
21
431
  }
22
- return {
432
+ return Object.values(sources).every((source) => typeof source.items === "function") ? {
23
433
  get,
24
434
  items
435
+ } : { get };
436
+ }
437
+ //#endregion
438
+ //#region src/core/split-source.ts
439
+ /** Split each item of a Source into parts, such as the sections of a Markdown file. Each part is an item. */
440
+ function splitSource(options) {
441
+ const parent = options.source;
442
+ const splitCaches = /* @__PURE__ */ new WeakMap();
443
+ async function partsOf(item) {
444
+ const parts = await options.split(item);
445
+ if (!Array.isArray(parts)) throw sourceError(`[vitehub] splitSource() split() must return an array for ${JSON.stringify(item.key)}.`);
446
+ const seen = /* @__PURE__ */ new Set();
447
+ return parts.map((part) => {
448
+ if (!part.key || part.key.includes("#")) throw sourceError(`[vitehub] splitSource() part key ${JSON.stringify(part.key)} in ${JSON.stringify(item.key)} must be a non-empty string without "#".`);
449
+ if (seen.has(part.key)) throw sourceError(`[vitehub] splitSource() returned the part key ${JSON.stringify(part.key)} twice for ${JSON.stringify(item.key)}.`);
450
+ seen.add(part.key);
451
+ const key = `${item.key}#${part.key}`;
452
+ const path = part.path ?? item.path;
453
+ const metadata = item.metadata === void 0 ? part.metadata : part.metadata === void 0 ? item.metadata : {
454
+ ...item.metadata,
455
+ ...part.metadata
456
+ };
457
+ return {
458
+ ...part,
459
+ key,
460
+ ...path === void 0 ? {} : { path },
461
+ ...metadata === void 0 ? {} : { metadata }
462
+ };
463
+ });
464
+ }
465
+ function cachedPartsOf(item, ctx) {
466
+ let splitCache = splitCaches.get(ctx);
467
+ if (!splitCache) {
468
+ splitCache = /* @__PURE__ */ new Map();
469
+ splitCaches.set(ctx, splitCache);
470
+ }
471
+ const cached = splitCache.get(item.key);
472
+ if (cached) return cached;
473
+ const result = partsOf(item);
474
+ splitCache.set(item.key, result);
475
+ return result;
476
+ }
477
+ async function parentItems(ctx) {
478
+ if (parent.getItems) return await parent.getItems(ctx);
479
+ const keys = await parent.getKeys(ctx);
480
+ return await Promise.all(keys.map((key) => parent.getItem(key, ctx)));
481
+ }
482
+ async function getItems(ctx) {
483
+ return (await Promise.all((await parentItems(ctx)).map((item) => cachedPartsOf(item, ctx)))).flat();
484
+ }
485
+ return {
486
+ name: options.name ?? parent.name,
487
+ ...parent.cache === void 0 ? {} : { cache: parent.cache },
488
+ ...parent.fingerprint === void 0 ? {} : { fingerprint: parent.fingerprint },
489
+ ...parent.resolveRevision ? { resolveRevision: (ctx) => parent.resolveRevision(ctx) } : {},
490
+ ...parent.prepare ? { prepare: (ctx) => parent.prepare(ctx) } : {},
491
+ async getKeys(ctx) {
492
+ return (await getItems(ctx)).map((part) => part.key);
493
+ },
494
+ async getItem(key, ctx) {
495
+ const id = String(key);
496
+ const at = id.lastIndexOf("#");
497
+ if (at < 1) throw sourceError(`[vitehub] splitSource() key ${JSON.stringify(id)} has no "#" between the item and the part.`);
498
+ const part = (await cachedPartsOf(await parent.getItem(id.slice(0, at), ctx), ctx)).find((candidate) => candidate.key === key);
499
+ if (!part) throw sourceError(`[vitehub] splitSource() could not find ${JSON.stringify(key)}.`);
500
+ return part;
501
+ },
502
+ getMeta(key, ctx) {
503
+ return (async () => {
504
+ const id = String(key);
505
+ const at = id.lastIndexOf("#");
506
+ if (at < 1) return void 0;
507
+ const parentKey = id.slice(0, at);
508
+ const cached = splitCaches.get(ctx)?.get(parentKey);
509
+ if (!cached) return await parent.getMeta?.(parentKey, ctx);
510
+ if (!(await cached).some((part) => part.key === key)) throw sourceError(`[vitehub] splitSource() could not find ${JSON.stringify(key)}.`);
511
+ return await parent.getMeta?.(parentKey, ctx);
512
+ })();
513
+ },
514
+ getItems
25
515
  };
26
516
  }
27
517
  //#endregion
28
518
  //#region src/core/define.ts
519
+ /** Define a loader. Open it with createSource() to bind its runtime context. */
29
520
  function defineSource(source) {
30
521
  return source;
31
522
  }
32
523
  function defineSources(sources) {
33
524
  return sources;
34
525
  }
35
- function createSource(definition, context) {
36
- return definition(context);
526
+ //#endregion
527
+ //#region src/core/reader.ts
528
+ function createSourceContext(name, context = {}) {
529
+ return {
530
+ abortSignal: context.abortSignal,
531
+ revision: context.revision,
532
+ rootDir: context.rootDir || process.cwd(),
533
+ source: context.source || name,
534
+ sourceRootDir: context.sourceRootDir,
535
+ workspace: context.workspace
536
+ };
537
+ }
538
+ function createMissingContentError(key) {
539
+ return sourceError(`[vitehub] Source item ${JSON.stringify(key)} does not provide readable content.`);
540
+ }
541
+ function isNestedUnder(path, prefix) {
542
+ return !prefix || path === prefix || path.startsWith(`${prefix}/`);
543
+ }
544
+ function createDirectorySet(paths, prefix) {
545
+ const directories = /* @__PURE__ */ new Set();
546
+ const start = prefix ? prefix.length + 1 : 0;
547
+ for (const path of paths) {
548
+ const normalized = normalizeSourcePath(path).split("/").filter(Boolean).join("/");
549
+ if (prefix && !normalized.startsWith(`${prefix}/`)) continue;
550
+ const end = normalized.indexOf("/", start);
551
+ if (end !== -1) directories.add(normalized.slice(0, end));
552
+ }
553
+ return directories;
554
+ }
555
+ function createSource(source, context) {
556
+ const ctx = createSourceContext(source.name, context);
557
+ let revisionPromise;
558
+ let preparePromise;
559
+ async function revision() {
560
+ if (ctx.revision) return ctx.revision;
561
+ revisionPromise ||= source.resolveRevision?.(ctx) ?? Promise.resolve(void 0);
562
+ const resolved = await revisionPromise;
563
+ if (resolved) ctx.revision = resolved;
564
+ return resolved;
565
+ }
566
+ async function ensurePrepared() {
567
+ await revision();
568
+ if (!source.prepare) return;
569
+ preparePromise ||= source.prepare(ctx);
570
+ await preparePromise;
571
+ }
572
+ async function keys() {
573
+ await ensurePrepared();
574
+ return await source.getKeys(ctx);
575
+ }
576
+ async function get(key) {
577
+ await ensurePrepared();
578
+ return await source.getItem(key, ctx);
579
+ }
580
+ return {
581
+ revision,
582
+ keys,
583
+ get,
584
+ async items() {
585
+ await ensurePrepared();
586
+ if (source.getItems) return await source.getItems(ctx);
587
+ return await Promise.all((await keys()).map(get));
588
+ },
589
+ async read(key, options) {
590
+ const item = await get(key);
591
+ if (item.content === void 0) throw createMissingContentError(key);
592
+ return decodeSourceContent(item.content, options);
593
+ },
594
+ async meta(key) {
595
+ await ensurePrepared();
596
+ return await source.getMeta?.(key, ctx);
597
+ },
598
+ async exists(key) {
599
+ return (await keys()).includes(key);
600
+ },
601
+ async list(prefix = "") {
602
+ await ensurePrepared();
603
+ const normalizedPrefix = prefix ? normalizeSafeSourcePath(prefix, { allowEmpty: true }).split("/").filter(Boolean).join("/") : "";
604
+ const sourceKeys = await keys();
605
+ const directories = createDirectorySet(sourceKeys, normalizedPrefix);
606
+ const result = /* @__PURE__ */ new Map();
607
+ for (const directory of directories) result.set(directory, {
608
+ key: directory,
609
+ type: "directory"
610
+ });
611
+ for (const key of sourceKeys) {
612
+ const normalizedKey = normalizeSourcePath(key).split("/").filter(Boolean).join("/");
613
+ if (normalizedKey === normalizedPrefix) continue;
614
+ if (!isNestedUnder(normalizedKey, normalizedPrefix)) continue;
615
+ if (normalizedKey.slice(normalizedPrefix.length).replace(/^\//, "").includes("/")) continue;
616
+ result.delete(normalizedKey);
617
+ result.set(key, {
618
+ key,
619
+ type: "file"
620
+ });
621
+ }
622
+ return [...result.values()].sort((left, right) => left.key.localeCompare(right.key));
623
+ }
624
+ };
625
+ }
626
+ //#endregion
627
+ //#region src/core/registry.ts
628
+ const sourceRegistry = /* @__PURE__ */ new Map();
629
+ function registerSource(name, source) {
630
+ sourceRegistry.set(name, source);
631
+ return source;
632
+ }
633
+ function registerSources(sources) {
634
+ for (const [name, source] of Object.entries(sources)) registerSource(name, source);
635
+ return sources;
636
+ }
637
+ function getRegisteredSource(name) {
638
+ const source = sourceRegistry.get(name);
639
+ if (!source) throw sourceNotFoundError(name);
640
+ return source;
641
+ }
642
+ function clearSources() {
643
+ sourceRegistry.clear();
644
+ }
645
+ /** Open a registered definition with the same lifecycle as direct Source readers. */
646
+ function useSource(name, context) {
647
+ return createSource(getRegisteredSource(name), {
648
+ ...context,
649
+ source: context?.source ?? name
650
+ });
37
651
  }
38
652
  //#endregion
39
653
  //#region src/ignores.ts
@@ -73,9 +687,4 @@ const sourceIgnores = Object.freeze({
73
687
  system
74
688
  });
75
689
  //#endregion
76
- //#region src/sources/custom.ts
77
- function custom(source) {
78
- return source;
79
- }
80
- //#endregion
81
- export { CollectionCursorError, clearSources, combineSources, createSource, custom, defineCollection, defineSource, defineSources, getRegisteredSource, registerSource, registerSources, sourceIgnores, useSource };
690
+ export { CollectionCursorError, array, clearSources, combineSources, createSource, defineCollection, defineSource, defineSources, getRegisteredSource, registerSource, registerSources, sourceIgnores, splitSource, useSource };
@@ -1,7 +1,5 @@
1
- import { r as Source } from "./types-Bu3WvNX9.js";
2
- import { n as FileSourceOptions } from "./file-EQ3AjVM6.js";
3
-
1
+ import { t as FileSource } from "./types-BigOktIj.js";
2
+ import { n as FileSourceOptions } from "./file-DadN9dbN.js";
4
3
  //#region src/sources/markdown.d.ts
5
- declare function markdown<const TKey extends string = string>(options: FileSourceOptions<TKey>): Source<TKey>;
6
- //#endregion
7
- export { markdown };
4
+ export declare function markdown<const TKey extends string = string>(options: FileSourceOptions<TKey>): FileSource<TKey>;
5
+ //#endregion