@hamur/content 0.0.0-stage → 0.0.1

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 (183) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/chunks/bun-render-65mwzeq2.js +58 -0
  4. package/dist/chunks/bun-render-7jxnxg3v.js +714 -0
  5. package/dist/chunks/bun-render-mxhn5twt.js +130 -0
  6. package/dist/chunks/bun-render-w7fh3fg7.js +36 -0
  7. package/dist/src/adapters/html.js +134 -0
  8. package/dist/src/adapters/preact.js +126 -0
  9. package/dist/src/adapters/react.js +116 -0
  10. package/dist/src/adapters/solid.js +153 -0
  11. package/dist/src/adapters/svelte.js +90 -0
  12. package/dist/src/adapters/vue.js +166 -0
  13. package/dist/src/index.js +2732 -0
  14. package/dist/src/query.js +97 -0
  15. package/dist/src/render.js +12 -0
  16. package/dist/src/server/index.js +349 -0
  17. package/dist/types/src/adapters/html.d.ts +54 -0
  18. package/dist/types/src/adapters/page.d.ts +21 -0
  19. package/dist/types/src/adapters/preact.d.ts +53 -0
  20. package/dist/types/src/adapters/prose.d.ts +21 -0
  21. package/dist/types/src/adapters/react.d.ts +53 -0
  22. package/dist/types/src/adapters/search.d.ts +12 -0
  23. package/dist/types/src/adapters/solid.d.ts +54 -0
  24. package/dist/types/src/adapters/svelte-page.d.ts +9 -0
  25. package/dist/types/src/adapters/svelte-search.d.ts +9 -0
  26. package/dist/types/src/adapters/svelte.d.ts +24 -0
  27. package/dist/types/src/adapters/vue.d.ts +189 -0
  28. package/dist/types/src/build/api.d.ts +24 -0
  29. package/dist/types/src/build/dev-route.d.ts +4 -0
  30. package/dist/types/src/build/dev.d.ts +48 -0
  31. package/dist/types/src/build/graphql.d.ts +10 -0
  32. package/dist/types/src/build/image.d.ts +16 -0
  33. package/dist/types/src/build/index.d.ts +76 -0
  34. package/dist/types/src/build/live.d.ts +6 -0
  35. package/dist/types/src/build/prerender.d.ts +8 -0
  36. package/dist/types/src/build/query.d.ts +10 -0
  37. package/dist/types/src/build/raw.d.ts +23 -0
  38. package/dist/types/src/build/search.d.ts +9 -0
  39. package/dist/types/src/build/types.d.ts +16 -0
  40. package/dist/types/src/component.d.ts +10 -0
  41. package/dist/types/src/config.d.ts +6 -0
  42. package/dist/types/src/define.d.ts +14 -0
  43. package/dist/types/src/error.d.ts +4 -0
  44. package/dist/types/src/image.d.ts +15 -0
  45. package/dist/types/src/index.d.ts +64 -0
  46. package/dist/types/src/loaders/data.d.ts +12 -0
  47. package/dist/types/src/loaders/file.d.ts +3 -0
  48. package/dist/types/src/loaders/git.d.ts +27 -0
  49. package/dist/types/src/loaders/glob.d.ts +14 -0
  50. package/dist/types/src/module.d.ts +3 -0
  51. package/dist/types/src/query.d.ts +17 -0
  52. package/dist/types/src/render.d.ts +9 -0
  53. package/dist/types/src/runtime/client.d.ts +25 -0
  54. package/dist/types/src/runtime/dev-client.d.ts +4 -0
  55. package/dist/types/src/runtime/dev-plugin.d.ts +12 -0
  56. package/dist/types/src/runtime/dev-store.d.ts +5 -0
  57. package/dist/types/src/runtime/live.d.ts +36 -0
  58. package/dist/types/src/runtime/navigation.d.ts +35 -0
  59. package/dist/types/src/runtime/page-plugin.d.ts +2 -0
  60. package/dist/types/src/runtime/page-source.d.ts +12 -0
  61. package/dist/types/src/runtime/query.d.ts +100 -0
  62. package/dist/types/src/runtime/raw-path.d.ts +2 -0
  63. package/dist/types/src/runtime/refresh-body.d.ts +4 -0
  64. package/dist/types/src/runtime/search-loaders.d.ts +7 -0
  65. package/dist/types/src/runtime/search-plugin.d.ts +2 -0
  66. package/dist/types/src/runtime/search-store.d.ts +19 -0
  67. package/dist/types/src/runtime/search.d.ts +28 -0
  68. package/dist/types/src/runtime/sections.d.ts +36 -0
  69. package/dist/types/src/runtime/server-store.d.ts +4 -0
  70. package/dist/types/src/runtime/store.d.ts +31 -0
  71. package/dist/types/src/server/door-dev-static.d.ts +3 -0
  72. package/dist/types/src/server/door-dev.d.ts +4 -0
  73. package/dist/types/src/server/door-static.d.ts +2 -0
  74. package/dist/types/src/server/door.d.ts +3 -0
  75. package/dist/types/src/server/endpoint.d.ts +1 -0
  76. package/dist/types/src/server/graphql.d.ts +24 -0
  77. package/dist/types/src/server/index.d.ts +10 -0
  78. package/dist/types/src/server/install.d.ts +1 -0
  79. package/dist/types/src/server/live.d.ts +10 -0
  80. package/dist/types/src/server/query.d.ts +15 -0
  81. package/dist/types/src/server/refresh.d.ts +2 -0
  82. package/dist/types/src/server/rest.d.ts +62 -0
  83. package/dist/types/src/server/search.d.ts +5 -0
  84. package/dist/types/src/server-config.d.ts +12 -0
  85. package/dist/types/src/source.d.ts +24 -0
  86. package/dist/types/src/types.d.ts +293 -0
  87. package/package.json +110 -4
  88. package/src/adapters/ContentRenderer.svelte +27 -0
  89. package/src/adapters/ProseA.svelte +11 -0
  90. package/src/adapters/ProseBlockquote.svelte +7 -0
  91. package/src/adapters/ProseCode.svelte +7 -0
  92. package/src/adapters/ProseEm.svelte +7 -0
  93. package/src/adapters/ProseH1.svelte +7 -0
  94. package/src/adapters/ProseH2.svelte +7 -0
  95. package/src/adapters/ProseH3.svelte +7 -0
  96. package/src/adapters/ProseH4.svelte +7 -0
  97. package/src/adapters/ProseH5.svelte +7 -0
  98. package/src/adapters/ProseH6.svelte +7 -0
  99. package/src/adapters/ProseHr.svelte +5 -0
  100. package/src/adapters/ProseImg.svelte +5 -0
  101. package/src/adapters/ProseLi.svelte +7 -0
  102. package/src/adapters/ProseOl.svelte +7 -0
  103. package/src/adapters/ProseP.svelte +7 -0
  104. package/src/adapters/ProsePre.svelte +21 -0
  105. package/src/adapters/ProseStrong.svelte +7 -0
  106. package/src/adapters/ProseTable.svelte +7 -0
  107. package/src/adapters/ProseUl.svelte +7 -0
  108. package/src/adapters/html.ts +152 -0
  109. package/src/adapters/page.ts +52 -0
  110. package/src/adapters/preact.ts +154 -0
  111. package/src/adapters/prose.ts +55 -0
  112. package/src/adapters/react.ts +142 -0
  113. package/src/adapters/search.ts +32 -0
  114. package/src/adapters/solid.ts +183 -0
  115. package/src/adapters/svelte-defaults.ts +41 -0
  116. package/src/adapters/svelte-page.ts +29 -0
  117. package/src/adapters/svelte-search.ts +36 -0
  118. package/src/adapters/svelte.ts +30 -0
  119. package/src/adapters/test/OwnA.svelte +7 -0
  120. package/src/adapters/test/OwnH1.svelte +7 -0
  121. package/src/adapters/test/OwnPre.svelte +7 -0
  122. package/src/adapters/test/support.ts +106 -0
  123. package/src/adapters/vue.ts +182 -0
  124. package/src/build/api.ts +201 -0
  125. package/src/build/dev-route.ts +5 -0
  126. package/src/build/dev.ts +299 -0
  127. package/src/build/graphql.ts +197 -0
  128. package/src/build/image.ts +60 -0
  129. package/src/build/index.ts +597 -0
  130. package/src/build/live.ts +34 -0
  131. package/src/build/prerender.ts +34 -0
  132. package/src/build/query.ts +70 -0
  133. package/src/build/raw.ts +157 -0
  134. package/src/build/search.ts +64 -0
  135. package/src/build/types.ts +108 -0
  136. package/src/component.ts +86 -0
  137. package/src/config.ts +156 -0
  138. package/src/define.ts +33 -0
  139. package/src/env.d.ts +34 -0
  140. package/src/error.ts +4 -0
  141. package/src/image.ts +41 -0
  142. package/src/index.ts +103 -0
  143. package/src/loaders/data.ts +186 -0
  144. package/src/loaders/file.ts +53 -0
  145. package/src/loaders/git.ts +266 -0
  146. package/src/loaders/glob.ts +179 -0
  147. package/src/module.ts +26 -0
  148. package/src/query.ts +82 -0
  149. package/src/render.ts +16 -0
  150. package/src/runtime/client.ts +75 -0
  151. package/src/runtime/dev-client.ts +6 -0
  152. package/src/runtime/dev-plugin.ts +64 -0
  153. package/src/runtime/dev-store.ts +19 -0
  154. package/src/runtime/live.ts +331 -0
  155. package/src/runtime/navigation.ts +225 -0
  156. package/src/runtime/page-plugin.ts +13 -0
  157. package/src/runtime/page-source.ts +22 -0
  158. package/src/runtime/query.ts +605 -0
  159. package/src/runtime/raw-path.ts +2 -0
  160. package/src/runtime/refresh-body.ts +22 -0
  161. package/src/runtime/search-loaders.ts +14 -0
  162. package/src/runtime/search-plugin.ts +6 -0
  163. package/src/runtime/search-store.ts +73 -0
  164. package/src/runtime/search.ts +126 -0
  165. package/src/runtime/sections.ts +155 -0
  166. package/src/runtime/server-store.ts +12 -0
  167. package/src/runtime/store.ts +59 -0
  168. package/src/server/door-dev-static.ts +6 -0
  169. package/src/server/door-dev.ts +7 -0
  170. package/src/server/door-static.ts +4 -0
  171. package/src/server/door.ts +6 -0
  172. package/src/server/endpoint.ts +17 -0
  173. package/src/server/graphql.ts +59 -0
  174. package/src/server/index.ts +17 -0
  175. package/src/server/install.ts +6 -0
  176. package/src/server/live.ts +51 -0
  177. package/src/server/query.ts +46 -0
  178. package/src/server/refresh.ts +19 -0
  179. package/src/server/rest.ts +157 -0
  180. package/src/server/search.ts +22 -0
  181. package/src/server-config.ts +24 -0
  182. package/src/source.ts +99 -0
  183. package/src/types.ts +282 -0
@@ -0,0 +1,19 @@
1
+ import { createError, defineHandler } from "hamur/server"
2
+ import { parseRefreshBody } from "../runtime/refresh-body.ts"
3
+ import { refreshContent } from "./live.ts"
4
+
5
+ /** `hamur dev` only; the dev runner has re-run the build loaders of the collections before this drops the live results. */
6
+ export const contentRefresh = defineHandler({
7
+ route: "/_hamur/content/refresh",
8
+ method: "POST",
9
+ raw: true,
10
+ async handler(_, { event }) {
11
+ try {
12
+ await refreshContent(parseRefreshBody(await event.request.text()))
13
+ } catch (error) {
14
+ if (error instanceof TypeError) throw createError({ status: 400, message: error.message })
15
+ throw error
16
+ }
17
+ return new Response(null, { status: 204 })
18
+ },
19
+ })
@@ -0,0 +1,157 @@
1
+ import { createError, type StandardJSONSchemaV1, type StandardSchemaV1 } from "hamur/server"
2
+ import {
3
+ QueryError,
4
+ runQuery,
5
+ type CollectionQuery,
6
+ type QueryClause,
7
+ type QueryCondition,
8
+ type QueryOperator,
9
+ } from "../runtime/query.ts"
10
+ import type { ContentStore } from "../runtime/store.ts"
11
+
12
+ /** The most entries one REST answer holds, and its `limit` when none is sent. */
13
+ export const REST_LIMIT = 100
14
+
15
+ type DocumentedSchema = StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV1<unknown, unknown>
16
+
17
+ const shown = (value: unknown): string => JSON.stringify(value) ?? String(value)
18
+
19
+ function fail(message: string): never {
20
+ throw new QueryError(message)
21
+ }
22
+
23
+ const WHERE = /^where\[([^[\]]+)\](?:\[([^[\]]+)\])?$/
24
+ const NO_VALUE = new Set(["IS NULL", "IS NOT NULL"])
25
+ const LISTS = new Set(["IN", "NOT IN"])
26
+
27
+ /** A query value is its JSON when it parses to a scalar or an array, else the text: `3` is a number, `"3"` the string. */
28
+ function readValue(text: string): unknown {
29
+ try {
30
+ const value: unknown = JSON.parse(text)
31
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return value
32
+ } catch {}
33
+ return text
34
+ }
35
+
36
+ const listOf = (value: unknown): string[] => (Array.isArray(value) ? value.map(String) : [String(value)])
37
+
38
+ /** A `where` condition from its field, operator (default `=`) and sent text or texts, read as `restQuery` reads a query string. */
39
+ export function condition(field: string, written: string | undefined, sent: unknown): QueryCondition {
40
+ const operator = (written === undefined ? "=" : written.toUpperCase()) as QueryOperator
41
+ const texts = listOf(sent)
42
+ if (NO_VALUE.has(operator))
43
+ return texts.every((text) => text === "") ? { field, operator } : { field, operator, value: readValue(texts[0]!) }
44
+ const values = texts.map(readValue)
45
+ if (values.length > 1) return { field, operator, value: values }
46
+ const value = values[0]
47
+ return { field, operator, value: LISTS.has(operator) && !Array.isArray(value) ? [value] : value }
48
+ }
49
+
50
+ function count(name: string, sent: unknown): number {
51
+ if (typeof sent !== "string" || !/^\d{1,15}$/.test(sent)) fail(`${name} must be a non-negative integer`)
52
+ return Number(sent)
53
+ }
54
+
55
+ function orderOf(sent: unknown): Array<[string, "ASC" | "DESC"]> {
56
+ return listOf(sent)
57
+ .flatMap((text) => text.split(","))
58
+ .map((item): [string, "ASC" | "DESC"] => {
59
+ const at = item.lastIndexOf(":")
60
+ const field = at === -1 ? item : item.slice(0, at)
61
+ const direction = at === -1 ? "asc" : item.slice(at + 1).toLowerCase()
62
+ if (field === "" || (direction !== "asc" && direction !== "desc"))
63
+ fail(`order takes field, field:asc or field:desc (got ${shown(item)})`)
64
+ return [field, direction === "asc" ? "ASC" : "DESC"]
65
+ })
66
+ }
67
+
68
+ /** The query string of `GET /api/_content/<collection>` as the engine's query; `limit` is capped at `REST_LIMIT`. */
69
+ export function restQuery(input: unknown): CollectionQuery {
70
+ const params = input !== null && typeof input === "object" ? (input as Record<string, unknown>) : {}
71
+ const where: QueryClause[] = []
72
+ const query: CollectionQuery = { limit: REST_LIMIT }
73
+ for (const key of Object.keys(params)) {
74
+ const sent = params[key]
75
+ if (key === "limit") query.limit = Math.min(count(key, sent), REST_LIMIT)
76
+ else if (key === "skip") query.skip = count(key, sent)
77
+ else if (key === "order") query.order = orderOf(sent)
78
+ else {
79
+ const match =
80
+ WHERE.exec(key) ??
81
+ fail(`unknown query parameter ${shown(key)}; use where[field], where[field][operator], order, limit and skip`)
82
+ where.push({ join: "AND", ...condition(match[1]!, match[2], sent) })
83
+ }
84
+ }
85
+ if (where.length) query.where = where
86
+ return query
87
+ }
88
+
89
+ /** Runs `query` (built by `build`, which may throw a `QueryError`) over an exposed collection: 404 for one the store does not expose, 400 for a query the engine refuses. REST and GraphQL both answer through it. */
90
+ export async function answerExposed(store: ContentStore, name: string, build: () => CollectionQuery): Promise<unknown> {
91
+ const meta = Object.hasOwn(store.collections, name) ? store.collections[name] : undefined
92
+ if (!meta?.expose) throw createError({ status: 404, message: `unknown collection ${shown(name)}` })
93
+ try {
94
+ return runQuery(name, meta, await store.entries(name), build())
95
+ } catch (error) {
96
+ if (error instanceof QueryError) throw createError({ status: 400, message: error.message })
97
+ throw error
98
+ }
99
+ }
100
+
101
+ /** The answer of `GET /api/_content/<name>`. */
102
+ export const answerRest = (store: ContentStore, name: string, input: unknown): Promise<unknown> =>
103
+ answerExposed(store, name, () => restQuery(input))
104
+
105
+ /** `GET /api/_content/<name>` of a name with no route: unknown, or not exposed. */
106
+ export function missingCollection(input: unknown): never {
107
+ const name = (input as { collection?: unknown } | null)?.collection
108
+ throw createError({ status: 404, message: `unknown collection ${shown(String(name))}` })
109
+ }
110
+
111
+ function documented(schema: Record<string, unknown>): DocumentedSchema {
112
+ return {
113
+ "~standard": {
114
+ version: 1,
115
+ vendor: "hamur-content",
116
+ validate: (value: unknown) => ({ value }),
117
+ jsonSchema: { input: () => schema, output: () => schema },
118
+ },
119
+ }
120
+ }
121
+
122
+ /** The query parameters as OpenAPI lists them; `where[...]` keys have no fixed names, so the operation's description gives them. */
123
+ export const restInput: DocumentedSchema = documented({
124
+ type: "object",
125
+ properties: {
126
+ order: {
127
+ type: "string",
128
+ description: "Comma-separated `field`, `field:asc` or `field:desc`; the collection's order without it.",
129
+ },
130
+ limit: {
131
+ type: "integer",
132
+ minimum: 0,
133
+ description: `At most ${REST_LIMIT} entries are answered: a larger value is cut to ${REST_LIMIT}, and no limit means ${REST_LIMIT}.`,
134
+ },
135
+ skip: { type: "integer", minimum: 0 },
136
+ },
137
+ })
138
+
139
+ /** The success body: an array of the collection's entries, each `item`. */
140
+ export const restOutput = (item: Record<string, unknown>): DocumentedSchema => documented(item)
141
+
142
+ const ERROR = {
143
+ type: "object",
144
+ required: ["status", "message"],
145
+ properties: { status: { type: "integer" }, message: { type: "string" } },
146
+ }
147
+
148
+ export const restResponses = {
149
+ 400: {
150
+ description: "An unknown field or operator, or a bad value",
151
+ content: { "application/json": { schema: ERROR } },
152
+ },
153
+ 404: { description: "An unknown or unexposed collection", content: { "application/json": { schema: ERROR } } },
154
+ }
155
+
156
+ export const REST_DESCRIPTION =
157
+ "Filter with `where[field]=value` (equal) or `where[field][operator]=value`, an operator of the queryCollection table (`>=`, `IN`, `LIKE`, …), URL-encoded. A value is read as JSON when it is a number, boolean, null, quoted string or array, else as text; `IN` and `BETWEEN` take a JSON array or repeated parameters. A field is a name or a dotted path."
@@ -0,0 +1,22 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import searches from "#hamur/content/search"
3
+ import type { HamurEvent } from "hamur/server"
4
+ import { searchIndex, type SearchHit } from "../runtime/search.ts"
5
+ import type { SearchOptions } from "../runtime/search-store.ts"
6
+
7
+ /** Ranks `query` with the collection's search index, the file the browser loads, so a handler and `useSearchCollection` give one answer. */
8
+ export async function searchCollection(
9
+ _event: HamurEvent,
10
+ name: string,
11
+ query: string,
12
+ { limit = 20 }: SearchOptions = {},
13
+ ): Promise<SearchHit[]> {
14
+ const load = Object.hasOwn(searches, name) ? searches[name] : undefined
15
+ if (!load)
16
+ throw new Error(
17
+ `searchCollection(${JSON.stringify(name)}): add ${JSON.stringify(name)} to content.search.collections`,
18
+ )
19
+ if (typeof query !== "string") throw new TypeError(`search: the query is a string (got ${JSON.stringify(query)})`)
20
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new TypeError("search: limit must be a non-negative integer")
21
+ return searchIndex((await load()).default, query, limit)
22
+ }
@@ -0,0 +1,24 @@
1
+ import type { ContentLoader } from "./types.ts"
2
+
3
+ export { defineCollection, defineContentConfig, defineLiveCollection, defineTransformer } from "./define.ts"
4
+ export { image } from "./image.ts"
5
+
6
+ /** The server never runs a build-time loader: these keep `content.config.ts` importable there without the build's Node modules. */
7
+ const buildOnly = (name: string): ContentLoader => ({
8
+ name,
9
+ load: () => Promise.reject(new Error(`content: ${name}() runs at build only`)),
10
+ })
11
+
12
+ export const glob = (): ContentLoader => buildOnly("glob")
13
+
14
+ export const file = (): ContentLoader => buildOnly("file")
15
+
16
+ export const fromComponent = (path: string) => ({
17
+ "~standard": {
18
+ version: 1,
19
+ vendor: "hamur",
20
+ validate() {
21
+ throw new Error(`fromComponent: ${path} is read only through content.config.ts at build`)
22
+ },
23
+ },
24
+ })
package/src/source.ts ADDED
@@ -0,0 +1,99 @@
1
+ import { existsSync } from "node:fs"
2
+ import { join, resolve, sep } from "node:path"
3
+ import type { Logger } from "hamur/server"
4
+ import { ContentError } from "./error.ts"
5
+ import { fetchRepository } from "./loaders/git.ts"
6
+ import type { CollectionSource, RemoteSourceOptions, SourceOptions } from "./types.ts"
7
+
8
+ export interface SourceFile {
9
+ /** The absolute directory `relative` is below. */
10
+ cwd: string
11
+ /** Absolute path. */
12
+ file: string
13
+ /** The path below the source's `cwd`, with `/`. */
14
+ relative: string
15
+ stem: string
16
+ extension: string
17
+ /** The page path from the source's `prefix` and `relative`. */
18
+ path: string
19
+ }
20
+
21
+ const PREFIX = /^(\d+)\./
22
+
23
+ export function pagePath(prefix: string, relative: string): string {
24
+ const segments = relative.split("/")
25
+ segments[segments.length - 1] = segments.at(-1)!.replace(/\.[^.]*$/, "")
26
+ const parts = segments.map((segment) => segment.replace(PREFIX, ""))
27
+ if (parts.at(-1) === "index") parts.pop()
28
+ const base = prefix.replace(/\/+$/, "")
29
+ return parts.length ? `${base}/${parts.join("/")}` : base || "/"
30
+ }
31
+
32
+ function compareSegment(a: string, b: string): number {
33
+ const left = PREFIX.exec(a)
34
+ const right = PREFIX.exec(b)
35
+ if (left && !right) return -1
36
+ if (!left && right) return 1
37
+ if (left && right && Number(left[1]) !== Number(right[1])) return Number(left[1]) - Number(right[1])
38
+ return a < b ? -1 : a > b ? 1 : 0
39
+ }
40
+
41
+ /** Source order: segment by segment, a number prefix numerically and before none, then by name. */
42
+ export function compareSource(a: string, b: string): number {
43
+ const left = a.split("/")
44
+ const right = b.split("/")
45
+ for (let index = 0; index < Math.min(left.length, right.length); index++) {
46
+ const order = compareSegment(left[index]!, right[index]!)
47
+ if (order !== 0) return order
48
+ }
49
+ return left.length - right.length
50
+ }
51
+
52
+ const options = (source: string | SourceOptions | RemoteSourceOptions): SourceOptions | RemoteSourceOptions =>
53
+ typeof source === "string" ? { include: source } : source
54
+
55
+ export interface RemoteContext {
56
+ /** `<cacheDir>`; default `<rootDir>/node_modules/.cache/hamur`. */
57
+ cacheDir?: string
58
+ logger?: Logger
59
+ }
60
+
61
+ /** The files of one collection: each source's files in source order, the sources in the order given; a remote source's files are below its cached copy. */
62
+ export async function setupSources(
63
+ rootDir: string,
64
+ source: CollectionSource,
65
+ remote: RemoteContext = {},
66
+ ): Promise<SourceFile[]> {
67
+ const files: SourceFile[] = []
68
+ const seen = new Set<string>()
69
+ for (const entry of (Array.isArray(source) ? source : [source]).map(options)) {
70
+ const cwd =
71
+ entry.repository !== undefined
72
+ ? await fetchRepository(entry, {
73
+ cacheDir: remote.cacheDir ?? join(rootDir, "node_modules/.cache/hamur"),
74
+ ...(remote.logger ? { logger: remote.logger } : {}),
75
+ })
76
+ : resolve(rootDir, "content", entry.cwd ?? "")
77
+ if (!existsSync(cwd)) {
78
+ if (entry.repository !== undefined)
79
+ throw new ContentError("HAMUR_E5368", `content: the cached copy of ${entry.repository} at ${cwd} is missing`)
80
+ continue
81
+ }
82
+ const exclude = (entry.exclude ?? []).map((pattern) => new Bun.Glob(pattern))
83
+ const found: string[] = []
84
+ for await (const match of new Bun.Glob(entry.include).scan({ cwd, onlyFiles: true })) {
85
+ const relative = match.split(sep).join("/")
86
+ if (!exclude.some((glob) => glob.match(relative))) found.push(relative)
87
+ }
88
+ for (const relative of found.sort(compareSource)) {
89
+ const file = resolve(cwd, relative)
90
+ if (seen.has(file)) continue
91
+ seen.add(file)
92
+ const dot = relative.lastIndexOf(".")
93
+ const extension = dot > relative.lastIndexOf("/") ? relative.slice(dot + 1) : ""
94
+ const stem = extension ? relative.slice(0, dot) : relative
95
+ files.push({ cwd, file, relative, stem, extension, path: pagePath(entry.prefix ?? "/", relative) })
96
+ }
97
+ }
98
+ return files
99
+ }
package/src/types.ts ADDED
@@ -0,0 +1,282 @@
1
+ import type { MarkdownDocument, MdHeading, MdRoot, TocLink } from "hamur/markdown"
2
+ import type { QueryCondition } from "./runtime/query.ts"
3
+ import type { Logger, StandardSchemaV1 } from "hamur/server"
4
+
5
+ /** Globs relative to `cwd`, which is relative to `<rootDir>/content`. */
6
+ export interface SourceOptions {
7
+ include: string
8
+ repository?: never
9
+ exclude?: string[]
10
+ /** The path prefix of a page collection; default `/`. */
11
+ prefix?: string
12
+ cwd?: string
13
+ }
14
+
15
+ /** Files of a GitHub or GitLab repository, downloaded at build; the globs are relative to the repository's root. */
16
+ export interface RemoteSourceOptions {
17
+ /** `https://github.com/<org>/<repo>` or `https://gitlab.com/<group>/<project>`. */
18
+ repository: string
19
+ /** Default the repository's default branch; set `branch` or `tag`, not both. */
20
+ branch?: string
21
+ tag?: string
22
+ include: string
23
+ exclude?: string[]
24
+ /** The path prefix of a page collection; default `/`. */
25
+ prefix?: string
26
+ cwd?: never
27
+ /** Sent as a header only (`Authorization: Bearer` on GitHub, `PRIVATE-TOKEN` on GitLab); never logged or cached. */
28
+ auth?: { token: string }
29
+ }
30
+
31
+ export type CollectionSource =
32
+ string | SourceOptions | RemoteSourceOptions | Array<string | SourceOptions | RemoteSourceOptions>
33
+
34
+ /** One entry a loader puts in the store. */
35
+ export interface LoaderEntry {
36
+ id: string
37
+ /** The entry's fields; validated through the collection's schema unless it is the output of `parseData`. */
38
+ data: Record<string, unknown>
39
+ /** Markdown source, frontmatter included; a page collection parses it into the page fields. */
40
+ body?: string
41
+ /** The entry's file: its extension is the entry's `extension`, and errors name it. */
42
+ file?: string
43
+ /** The same digest as in the last build skips the entry's parse and reuses its index entry. */
44
+ digest?: string
45
+ /** Default `id`. */
46
+ stem?: string
47
+ /** A page's path; default `/<id>`. */
48
+ path?: string
49
+ /** The `.navigation.yml` data of the directories above a page, by directory stem; the glob loader sets it. */
50
+ navigationDirs?: Record<string, Record<string, unknown>>
51
+ }
52
+
53
+ export interface LoaderContext {
54
+ collection: string
55
+ type: "page" | "data"
56
+ rootDir: string
57
+ store: {
58
+ set(entry: LoaderEntry): void
59
+ delete(id: string): void
60
+ keys(): string[]
61
+ clear(): void
62
+ }
63
+ /** Strings kept per collection between builds, in the content index. */
64
+ meta: { get(key: string): string | undefined; set(key: string, value: string): void }
65
+ /** Validates through the collection's schema and returns the output, or throws the validation message. */
66
+ parseData(entry: { id: string; data: unknown; file?: string }): Promise<Record<string, unknown>>
67
+ parseMarkdown(source: string, options?: { file?: string }): Promise<MarkdownDocument>
68
+ digest(value: string | Uint8Array): string
69
+ /** `content.csv` with its defaults: how the file and glob loaders read `.csv`. */
70
+ csv: { delimiter: string; header: boolean }
71
+ logger: Logger
72
+ /** The config's transformers; a loader reads a file whose extension one of their `parse` lists through it. */
73
+ transformers: readonly Transformer[]
74
+ /** Runs the `content:file:beforeParse` hooks, then returns the file's body, which a hook may have changed. */
75
+ beforeParse(file: ContentFile): Promise<string>
76
+ }
77
+
78
+ /** The file a transformer's `parse` and the `content:file:*` hooks read. */
79
+ export interface ContentFile {
80
+ /** The entry id the file gives. */
81
+ id: string
82
+ /** From the root, with `/`: `content/notes/a.txt`. */
83
+ path: string
84
+ /** Without the dot. */
85
+ extension: string
86
+ /** The file's text. */
87
+ body: string
88
+ }
89
+
90
+ /** `defineTransformer`'s argument. */
91
+ export interface Transformer {
92
+ name: string
93
+ /** With the dot: `[".adoc"]`. With `parse`, the extensions are read from every collection's sources. */
94
+ extensions: string[]
95
+ /** Reads a file of one of `extensions` into the entry's fields; a string `body` field is the Markdown a page collection parses. */
96
+ parse?(file: ContentFile): Record<string, unknown> | Promise<Record<string, unknown>>
97
+ /** Runs on every parsed entry after the schema, in list order, and returns the entry. */
98
+ transform?(entry: ContentEntry): Record<string, unknown> | Promise<Record<string, unknown>>
99
+ }
100
+
101
+ export interface ContentLoader {
102
+ name: string
103
+ load(ctx: LoaderContext): Promise<void>
104
+ }
105
+
106
+ interface CollectionBase {
107
+ type: "page" | "data"
108
+ /** Validates each entry's frontmatter or data at build; its output replaces the input. */
109
+ schema?: StandardSchemaV1
110
+ /** `false` keeps the collection server-only; default `true`. */
111
+ expose?: boolean
112
+ /** The collection's default order; default the source order. */
113
+ order?: [field: string, direction: "ASC" | "DESC"]
114
+ }
115
+
116
+ export type CollectionDefinition = CollectionBase &
117
+ ({ source: CollectionSource; loader?: never } | { loader: ContentLoader; source?: never })
118
+
119
+ /** How long a live result may be reused, and what it depends on. */
120
+ export interface CacheHint {
121
+ tags?: string[]
122
+ /** Seconds; with it, `getLiveCollection` and `getLiveEntry` keep the result in the `cache` storage mount that long. */
123
+ maxAge?: number
124
+ lastModified?: Date
125
+ }
126
+
127
+ /** One entry a live loader returns. */
128
+ export interface LiveLoaderEntry<D extends object = Record<string, unknown>> {
129
+ id: string
130
+ /** Validated through the collection's schema when it has one. */
131
+ data: D
132
+ /** Markdown source (parsed on the bun preset only) or a Markdown AST. */
133
+ body?: string | MdRoot
134
+ cacheHint?: CacheHint
135
+ }
136
+
137
+ /** Fetches a live collection at request time. */
138
+ export interface LiveLoader<CollectionFilter = any, EntryFilter = any, D extends object = object> {
139
+ name?: string
140
+ loadCollection(
141
+ filter: CollectionFilter,
142
+ ):
143
+ | { entries: LiveLoaderEntry<D>[]; cacheHint?: CacheHint }
144
+ | Promise<{ entries: LiveLoaderEntry<D>[]; cacheHint?: CacheHint }>
145
+ loadEntry(filter: EntryFilter): LiveLoaderEntry<D> | undefined | Promise<LiveLoaderEntry<D> | undefined>
146
+ }
147
+
148
+ /** What `defineLiveCollection` returns; never written into the content index. */
149
+ export interface LiveCollectionDefinition<
150
+ L extends LiveLoader = LiveLoader,
151
+ S extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined,
152
+ > {
153
+ live: true
154
+ loader: L
155
+ schema?: S
156
+ }
157
+
158
+ export interface ContentConfig<
159
+ C extends Record<string, CollectionDefinition | LiveCollectionDefinition> = Record<string, CollectionDefinition>,
160
+ > {
161
+ collections: C
162
+ /** Code that reads more file types or reshapes every entry. */
163
+ transformers?: Transformer[]
164
+ }
165
+
166
+ /** `content.config.ts` as the build reads it: the live collections apart from the others. */
167
+ export interface LoadedContentConfig extends ContentConfig {
168
+ live: Record<string, LiveCollectionDefinition>
169
+ }
170
+
171
+ /** The `content` key of `hamur.config.ts`. */
172
+ export interface ContentOptions {
173
+ /** How `queryCollection` runs in the browser: `"api"` posts to `/_hamur/content/query`, `"local"` fetches the collection once. Default `"api"`, `"local"` on the `static` preset. */
174
+ clientQuery?: "api" | "local"
175
+ /** The page collections that get a search index at build; each must be exposed. Default `false`. */
176
+ search?: { collections: string[] } | false
177
+ /** Entries per chunk of a collection in the server bundle: a positive integer. Default `1000`. */
178
+ chunkSize?: number
179
+ /** How `.csv` files are read: `delimiter` one character, default `","`; `header` whether the first row names the columns, default `true`. */
180
+ csv?: { delimiter?: string; header?: boolean }
181
+ /** Adds the `path` of every page entry to the prerender routes. Default `true` on the `static` preset, else `false`. */
182
+ prerender?: boolean
183
+ /** Serves each page entry's source at `<path>.md`: `true` the file on disk, `"body"` the Markdown its loader gave. Default `false`. */
184
+ raw?: boolean | "body"
185
+ /** Serves `/llms.txt` and `/llms-full.txt` from page collections. */
186
+ llms?: LlmsOptions
187
+ /** `rest` serves `GET /api/_content/<collection>` for every exposed collection; `graphql` adds them to the app's GraphQL schema. Both default `false`. */
188
+ api?: { rest?: boolean; graphql?: boolean }
189
+ }
190
+
191
+ /** The `llms.txt` of the site. */
192
+ export interface LlmsOptions {
193
+ title: string
194
+ description?: string
195
+ sections: Array<{
196
+ title: string
197
+ /** A page collection. */
198
+ collection: string
199
+ /** A condition or conditions joined by `AND`; default every page of the collection. */
200
+ where?: QueryCondition | QueryCondition[]
201
+ }>
202
+ }
203
+
204
+ /** The fields every entry has, without the index signature that lets an untyped entry carry any other field. */
205
+ export interface DataFields {
206
+ /** The name of the collection the entry belongs to. */
207
+ collection: string
208
+ /** The stem, or `<stem>/<index>` for an item of an array file. */
209
+ id: string
210
+ /** The file's path below the source's `cwd` without its extension, number prefixes kept. */
211
+ stem: string
212
+ extension: string
213
+ }
214
+
215
+ export interface PageFields extends DataFields {
216
+ path: string
217
+ title: string | undefined
218
+ description: string | undefined
219
+ seo: { title?: string; description?: string; [field: string]: unknown }
220
+ navigation: boolean | { title?: string; icon?: string }
221
+ draft: boolean
222
+ navigationDirs?: Record<string, Record<string, unknown>>
223
+ body: MdRoot
224
+ excerpt: MdRoot | undefined
225
+ headings: MdHeading[]
226
+ toc: TocLink[]
227
+ readingTime: number
228
+ }
229
+
230
+ export interface DataEntry extends DataFields {
231
+ [field: string]: unknown
232
+ }
233
+
234
+ export interface PageEntry extends DataEntry, PageFields {}
235
+
236
+ /** A schema output as the index stores it: JSON, so a `Date` is its ISO string. */
237
+ export type Serialized<T> = T extends Date
238
+ ? string
239
+ : T extends (...args: never[]) => unknown
240
+ ? T
241
+ : T extends object
242
+ ? { [K in keyof T]: Serialized<T[K]> }
243
+ : T
244
+
245
+ /** The item type of a collection definition: its page or data fields and the schema's output; `Record<string, unknown>` without a schema. */
246
+ export type CollectionItemOf<D> = (D extends { type: "page" } ? PageFields : DataFields) &
247
+ (D extends { schema: infer S extends StandardSchemaV1 }
248
+ ? Serialized<StandardSchemaV1.InferOutput<S>>
249
+ : Record<string, unknown>)
250
+
251
+ export type ContentEntry = PageEntry | DataEntry
252
+
253
+ type LiveSchemaOf<D> = D extends { schema?: infer S } ? Exclude<S, undefined> : never
254
+ type LiveLoaderDataOf<D> = D extends { loader: { loadEntry(filter: any): infer R } }
255
+ ? NonNullable<Awaited<R>> extends { data: infer T }
256
+ ? T
257
+ : Record<string, unknown>
258
+ : Record<string, unknown>
259
+
260
+ /** The `data` of a live collection's entry: the schema's output, else the loader's `data`, with `Date` written as `string`. */
261
+ export type LiveCollectionItemOf<D> = [LiveSchemaOf<D>] extends [never]
262
+ ? Serialized<LiveLoaderDataOf<D>>
263
+ : LiveSchemaOf<D> extends StandardSchemaV1
264
+ ? Serialized<StandardSchemaV1.InferOutput<LiveSchemaOf<D>>>
265
+ : Serialized<LiveLoaderDataOf<D>>
266
+
267
+ /** An entry `getLiveCollection` and `getLiveEntry` give. */
268
+ export interface LiveEntry<T = Record<string, unknown>> {
269
+ id: string
270
+ data: T
271
+ /** The loader's Markdown AST, or its Markdown source parsed. */
272
+ body?: MdRoot
273
+ cacheHint?: CacheHint
274
+ }
275
+
276
+ export type LiveCollectionResult<T = Record<string, unknown>> =
277
+ | { entries: LiveEntry<T>[]; error: undefined; cacheHint: CacheHint }
278
+ | { entries: undefined; error: Error; cacheHint: CacheHint }
279
+
280
+ export type LiveEntryResult<T = Record<string, unknown>> =
281
+ | { entry: LiveEntry<T> | undefined; error: undefined; cacheHint: CacheHint }
282
+ | { entry: undefined; error: Error; cacheHint: CacheHint }