@hamur/content 0.0.0-stage → 0.0.2

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 +140 -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,182 @@
1
+ import {
2
+ computed,
3
+ defineComponent,
4
+ getCurrentScope,
5
+ h,
6
+ onMounted,
7
+ onScopeDispose,
8
+ shallowRef,
9
+ type Component,
10
+ type ComputedRef,
11
+ type PropType,
12
+ } from "vue"
13
+ import { Link, MarkdownRenderer, useApp, useAsyncData, useHead, useRoute, useSeoMeta } from "@hamur/adapter-vue"
14
+ import type { MdRoot } from "hamur/markdown"
15
+ import type { CollectionName } from "../index.ts"
16
+ import type { PageEntry, PageFields } from "../types.ts"
17
+ import { checkPageCollection, loadPage, pageHead, pageKey, pageSeo, settledPage, type ContentPage } from "./page.ts"
18
+ import { isInternal, prepare } from "./prose.ts"
19
+ import {
20
+ ignore,
21
+ searchCollectionOf,
22
+ type SearchHit,
23
+ type SearchOptions,
24
+ type SearchStatus,
25
+ type UseSearchCollectionOptions,
26
+ } from "./search.ts"
27
+
28
+ export type { ContentPage, SearchHit, SearchOptions, SearchStatus, UseSearchCollectionOptions }
29
+
30
+ export interface ContentRendererProps {
31
+ /** A page entry, which renders its `body`, or a Markdown AST. */
32
+ value: PageFields | MdRoot
33
+ /** Markdown components by kebab-case name and prose components by `Prose<Tag>` name; `false` registers none. */
34
+ components?: Record<string, Component> | false
35
+ /** The wrapper element; `"div"` by default. */
36
+ tag?: string
37
+ /** Renders the entry's `excerpt` instead of its `body`. */
38
+ excerpt?: boolean
39
+ /** Space-separated tags whose element is dropped and whose children are kept. */
40
+ unwrap?: string
41
+ }
42
+
43
+ const plain = (tag: string, name: string) =>
44
+ defineComponent({
45
+ name,
46
+ setup(_props, { slots }) {
47
+ return () => h(tag, null, slots.default?.())
48
+ },
49
+ })
50
+
51
+ export const ProseH1 = plain("h1", "ProseH1")
52
+ export const ProseH2 = plain("h2", "ProseH2")
53
+ export const ProseH3 = plain("h3", "ProseH3")
54
+ export const ProseH4 = plain("h4", "ProseH4")
55
+ export const ProseH5 = plain("h5", "ProseH5")
56
+ export const ProseH6 = plain("h6", "ProseH6")
57
+ export const ProseP = plain("p", "ProseP")
58
+ export const ProseUl = plain("ul", "ProseUl")
59
+ export const ProseOl = plain("ol", "ProseOl")
60
+ export const ProseLi = plain("li", "ProseLi")
61
+ export const ProseBlockquote = plain("blockquote", "ProseBlockquote")
62
+ export const ProseCode = plain("code", "ProseCode")
63
+ export const ProseImg = plain("img", "ProseImg")
64
+ export const ProseTable = plain("table", "ProseTable")
65
+ export const ProseHr = plain("hr", "ProseHr")
66
+ export const ProseStrong = plain("strong", "ProseStrong")
67
+ export const ProseEm = plain("em", "ProseEm")
68
+
69
+ /** An internal `href` is a `Link`, as `MarkdownRenderer` writes it. */
70
+ export const ProseA = defineComponent({
71
+ name: "ProseA",
72
+ inheritAttrs: false,
73
+ props: { href: { type: String, default: undefined } },
74
+ setup(props, { attrs, slots }) {
75
+ return () =>
76
+ isInternal(props.href)
77
+ ? h(Link, { ...attrs, to: props.href }, { default: slots.default })
78
+ : h("a", { href: props.href, ...attrs }, slots.default?.())
79
+ },
80
+ })
81
+
82
+ export const ProsePre = defineComponent({
83
+ name: "ProsePre",
84
+ props: {
85
+ language: { type: String, default: undefined },
86
+ filename: { type: String, default: undefined },
87
+ highlights: { type: Array as PropType<number[]>, default: undefined },
88
+ code: { type: String, default: undefined },
89
+ },
90
+ setup(props, { slots }) {
91
+ return () => h("pre", props.filename === undefined ? null : { "data-filename": props.filename }, slots.default?.())
92
+ },
93
+ })
94
+
95
+ const DEFAULTS = {
96
+ a: ProseA,
97
+ h1: ProseH1,
98
+ h2: ProseH2,
99
+ h3: ProseH3,
100
+ h4: ProseH4,
101
+ h5: ProseH5,
102
+ h6: ProseH6,
103
+ p: ProseP,
104
+ ul: ProseUl,
105
+ ol: ProseOl,
106
+ li: ProseLi,
107
+ blockquote: ProseBlockquote,
108
+ pre: ProsePre,
109
+ code: ProseCode,
110
+ img: ProseImg,
111
+ table: ProseTable,
112
+ hr: ProseHr,
113
+ strong: ProseStrong,
114
+ em: ProseEm,
115
+ }
116
+
117
+ /** A page entry's body, or a Markdown AST, through `MarkdownRenderer` with the prose components of `components`. */
118
+ export const ContentRenderer = defineComponent({
119
+ name: "ContentRenderer",
120
+ props: {
121
+ value: { type: [Array, Object] as PropType<PageFields | MdRoot>, default: undefined },
122
+ components: { type: [Object, Boolean] as PropType<Record<string, Component> | false>, default: undefined },
123
+ tag: { type: String, default: "div" },
124
+ excerpt: { type: Boolean, default: false },
125
+ unwrap: { type: String, default: undefined },
126
+ },
127
+ setup(props) {
128
+ return () => {
129
+ const prepared = prepare({
130
+ value: props.value,
131
+ components: props.components,
132
+ defaults: DEFAULTS,
133
+ excerpt: props.excerpt,
134
+ unwrap: props.unwrap,
135
+ })
136
+ return prepared
137
+ ? h(props.tag, [h(MarkdownRenderer, { value: prepared.root, components: prepared.components })])
138
+ : null
139
+ }
140
+ },
141
+ })
142
+
143
+ export interface UseSearchCollectionResult {
144
+ status: ComputedRef<SearchStatus>
145
+ search(query: string, options?: SearchOptions): Promise<SearchHit[]>
146
+ init(): Promise<void>
147
+ }
148
+
149
+ /** The collection's search index, loaded on the first `search()` or `init()`, or at mount with `immediate`; `status` is a read-only ref. */
150
+ export function useSearchCollection(
151
+ name: string,
152
+ { immediate = false }: UseSearchCollectionOptions = {},
153
+ ): UseSearchCollectionResult {
154
+ const collection = searchCollectionOf(name)
155
+ const status = shallowRef<SearchStatus>(collection.status)
156
+ const stop = collection.subscribe(() => {
157
+ status.value = collection.status
158
+ })
159
+ if (getCurrentScope()) onScopeDispose(stop)
160
+ if (immediate) onMounted(() => void collection.init().catch(ignore))
161
+ return { status: computed(() => status.value), search: collection.search, init: collection.init }
162
+ }
163
+
164
+ /** Awaited in `setup`, resolves to a ref of the entry of `collection` whose `path` is the route path; rejects with the 404 when there is none. */
165
+ export async function useContentPage<N extends CollectionName>(collection: N): Promise<ComputedRef<ContentPage<N>>> {
166
+ checkPageCollection(collection)
167
+ const route = useRoute()
168
+ const store = useApp().asyncData
169
+ const key = () => pageKey(collection, route.path)
170
+ const { data, error, status } = useAsyncData<PageEntry | null>(key, () => loadPage(collection, route.path))
171
+ // A head entry made after an await has no component to belong to, so it is made first and reads what has settled.
172
+ useSeoMeta(() => pageSeo(status.value === "success" ? data.value : undefined))
173
+ useHead(() => pageHead(status.value === "success" ? data.value : undefined))
174
+ await store.get(key())?.promise
175
+ let last: PageEntry | undefined
176
+ const page = computed(() => {
177
+ last = settledPage(route.path, { data: data.value, error: error.value, status: status.value }) ?? last
178
+ return last
179
+ })
180
+ void page.value
181
+ return page as unknown as ComputedRef<ContentPage<N>>
182
+ }
@@ -0,0 +1,201 @@
1
+ import { join, relative, sep } from "node:path"
2
+ import { DiagnosticError, addServer, addTemplate, createResolver, type HamurContext } from "hamur/kit"
3
+ import type { StandardJSONSchemaV1 } from "hamur/server"
4
+ import type { CollectionDefinition, ContentConfig } from "../types.ts"
5
+
6
+ const shown = (value: unknown): string => JSON.stringify(value) ?? String(value)
7
+
8
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
9
+ value !== null && typeof value === "object" && !Array.isArray(value)
10
+
11
+ /** `content.api`, both surfaces off by default; `graphql` needs `server.graphql` on. */
12
+ export function resolveApi(
13
+ value: unknown,
14
+ preset: string,
15
+ serverGraphQL: boolean,
16
+ ): { rest: boolean; graphql: boolean } {
17
+ if (value === undefined) return { rest: false, graphql: false }
18
+ if (!isRecord(value))
19
+ throw new DiagnosticError(
20
+ "HAMUR_E5335",
21
+ `content.api must be { rest?: boolean, graphql?: boolean } (got ${shown(value)})`,
22
+ )
23
+ for (const key of Object.keys(value))
24
+ if (key !== "rest" && key !== "graphql")
25
+ throw new DiagnosticError("HAMUR_E5335", `content.api has no key ${shown(key)}; it takes rest and graphql`)
26
+ for (const key of ["rest", "graphql"])
27
+ if (value[key] !== undefined && typeof value[key] !== "boolean")
28
+ throw new DiagnosticError("HAMUR_E5335", `content.api.${key} must be a boolean (got ${shown(value[key])})`)
29
+ const rest = value.rest === true
30
+ const graphql = value.graphql === true
31
+ if (rest && preset === "static")
32
+ throw new DiagnosticError("HAMUR_E5336", "content.api.rest needs a server; the static preset serves no route")
33
+ if (graphql && !serverGraphQL) throw new DiagnosticError("HAMUR_E5337", "content.api.graphql needs server.graphql on")
34
+ return { rest, graphql }
35
+ }
36
+
37
+ const STRING = { type: "string" }
38
+ const DATA_FIELDS: Record<string, unknown> = { collection: STRING, id: STRING, stem: STRING, extension: STRING }
39
+ const PAGE_FIELDS: Record<string, unknown> = {
40
+ ...DATA_FIELDS,
41
+ path: STRING,
42
+ title: STRING,
43
+ description: STRING,
44
+ seo: { type: "object" },
45
+ navigation: { type: ["boolean", "object"] },
46
+ draft: { type: "boolean" },
47
+ navigationDirs: { type: "object" },
48
+ body: { type: "array" },
49
+ excerpt: { type: "array" },
50
+ headings: { type: "array" },
51
+ toc: { type: "array" },
52
+ readingTime: { type: "number" },
53
+ }
54
+
55
+ /** The schema's output as JSON Schema, or undefined when it has none or the conversion throws. */
56
+ export function outputSchema(collection: CollectionDefinition): Record<string, unknown> | undefined {
57
+ const converter = (collection.schema as unknown as Partial<StandardJSONSchemaV1> | undefined)?.["~standard"]
58
+ ?.jsonSchema
59
+ if (typeof converter?.output !== "function") return undefined
60
+ try {
61
+ const schema = converter.output({ target: "draft-2020-12" })
62
+ return isRecord(schema) ? schema : undefined
63
+ } catch {
64
+ return undefined
65
+ }
66
+ }
67
+
68
+ const OPEN_KEYS = new Set(["additionalProperties", "unevaluatedProperties"])
69
+
70
+ /** A `$ref` into the user schema's root, moved under `$defs/<entry>` so it still points at the entry. */
71
+ function rerooted(value: unknown, entry: string): unknown {
72
+ if (Array.isArray(value)) return value.map((item) => rerooted(item, entry))
73
+ if (!isRecord(value)) return value
74
+ const result: Record<string, unknown> = {}
75
+ for (const [key, child] of Object.entries(value)) {
76
+ const moved =
77
+ key === "$ref" &&
78
+ typeof child === "string" &&
79
+ (child === "#" || (child.startsWith("#/") && !child.startsWith("#/$defs/")))
80
+ ? `#/$defs/${entry}${child.slice(1)}`
81
+ : rerooted(child, entry)
82
+ Object.defineProperty(result, key, { value: moved, enumerable: true, writable: true, configurable: true })
83
+ }
84
+ return result
85
+ }
86
+
87
+ /**
88
+ * The array of entries one REST answer holds. The entry is its own `$defs` member, so OpenAPI makes it a
89
+ * component and a recursive schema's `#` still means the entry: the collection schema's output with the built fields
90
+ * merged into its `properties` and `required`, and without `additionalProperties` at its root, which a strict schema
91
+ * sets to `false` and every entry, holding the built fields, would then fail.
92
+ */
93
+ export function restSchema(name: string, collection: CollectionDefinition): Record<string, unknown> {
94
+ const page = collection.type === "page"
95
+ const builtRequired = page
96
+ ? ["collection", "id", "stem", "extension", "path"]
97
+ : ["collection", "id", "stem", "extension"]
98
+ const builtProperties = page ? PAGE_FIELDS : DATA_FIELDS
99
+ const own = outputSchema(collection)
100
+ const { $schema: _, $defs, ...rest } = own ?? {}
101
+ const defs = isRecord($defs) ? $defs : {}
102
+ let entry = `Content${name[0]!.toUpperCase()}${name.slice(1)}`
103
+ while (Object.hasOwn(defs, entry)) entry = `${entry}_`
104
+ const open = Object.fromEntries(Object.entries(rest).filter(([key]) => !OPEN_KEYS.has(key)))
105
+ let schema: Record<string, unknown>
106
+ if (!own) schema = { type: "object", required: builtRequired, properties: builtProperties }
107
+ else if (isRecord(open.properties) || open.type === "object") {
108
+ const required = [
109
+ ...(Array.isArray(open.required) ? open.required.filter((key) => !builtRequired.includes(key)) : []),
110
+ ...builtRequired,
111
+ ]
112
+ schema = {
113
+ ...open,
114
+ type: "object",
115
+ properties: { ...(isRecord(open.properties) ? open.properties : {}), ...builtProperties },
116
+ required,
117
+ }
118
+ } else schema = { allOf: [{ type: "object", required: builtRequired, properties: builtProperties }, open] }
119
+ return { type: "array", items: { $ref: `#/$defs/${entry}` }, $defs: rerooted({ ...defs, [entry]: schema }, entry) }
120
+ }
121
+
122
+ const exportOf = (name: string): string => `contentRest${name[0]!.toUpperCase()}${name.slice(1)}`
123
+
124
+ /** The collections REST serves: every exposed one (live collections are not in `collections`). */
125
+ export const restCollections = (config: ContentConfig): string[] =>
126
+ Object.entries(config.collections)
127
+ .filter(([, { expose = true }]) => expose)
128
+ .map(([name]) => name)
129
+
130
+ /** `.hamur/content/server/rest.ts`: one `GET /api/_content/<name>` per exposed collection, and `/api/_content/:collection` answering 404 for any other name. */
131
+ export function restModule(config: ContentConfig, runtime: string): string {
132
+ const q = JSON.stringify
133
+ const handlers = restCollections(config).map((name) =>
134
+ [
135
+ `export const ${exportOf(name)} = defineHandler({`,
136
+ ` route: ${q(`/api/_content/${name}`)},`,
137
+ ` method: "GET",`,
138
+ " input: restInput,",
139
+ ` output: restOutput(${q(restSchema(name, config.collections[name]!))}),`,
140
+ ` meta: { summary: ${q(`Query the ${name} collection`)}, description: REST_DESCRIPTION, tags: ["content"], operationId: ${q(`getContent${exportOf(name).slice("contentRest".length)}`)}, responses: restResponses },`,
141
+ ` handler: (input) => answerRest(store, ${q(name)}, input),`,
142
+ "});",
143
+ "",
144
+ ].join("\n"),
145
+ )
146
+ return [
147
+ `import store from "#hamur/content/store";`,
148
+ `import { defineHandler } from "hamur/server";`,
149
+ `import { answerRest, missingCollection, REST_DESCRIPTION, restInput, restOutput, restResponses } from ${q(runtime)};`,
150
+ "",
151
+ ...handlers,
152
+ "export const contentRest = defineHandler({",
153
+ ` route: "/api/_content/:collection",`,
154
+ ` method: "GET",`,
155
+ " meta: { hidden: true },",
156
+ " handler: (input) => missingCollection(input),",
157
+ "});",
158
+ "",
159
+ ].join("\n")
160
+ }
161
+
162
+ const posix = (path: string): string => path.split(sep).join("/")
163
+
164
+ /** The generated door: the package door's handlers by relative path (a door follows only those), then the REST handlers. */
165
+ export function restDoor(config: ContentConfig, serverDir: string, doorDir: string, dev: boolean): string {
166
+ const from = (file: string) => {
167
+ const path = posix(relative(doorDir, join(serverDir, file)))
168
+ return JSON.stringify(path.startsWith(".") ? path : `./${path}`)
169
+ }
170
+ return [
171
+ `import { defineServer } from "hamur/server";`,
172
+ `import { installStore } from ${from("install.ts")};`,
173
+ "",
174
+ `export { contentQuery } from ${from("endpoint.ts")};`,
175
+ ...(dev ? [`export { contentRefresh } from ${from("refresh.ts")};`] : []),
176
+ `export { ${[...restCollections(config).map(exportOf), "contentRest"].join(", ")} } from "./rest.ts";`,
177
+ "",
178
+ "export default defineServer({ plugins: [installStore] });",
179
+ "",
180
+ ].join("\n")
181
+ }
182
+
183
+ const FOLDER = "content/server"
184
+
185
+ /** With `content.api.rest`, the module's door is generated, so each collection's route is a literal. */
186
+ export function setupRest(config: ContentConfig, hamur: HamurContext): void {
187
+ const resolver = createResolver(import.meta.url)
188
+ const serverDir = resolver.resolve("../server")
189
+ const doorDir = join(hamur.options.buildDir, FOLDER)
190
+ addTemplate({
191
+ filename: `${FOLDER}/rest.ts`,
192
+ write: true,
193
+ getContents: () => restModule(config, resolver.resolve("../server/rest.ts")),
194
+ })
195
+ addTemplate({
196
+ filename: `${FOLDER}/door.ts`,
197
+ write: true,
198
+ getContents: () => restDoor(config, serverDir, doorDir, hamur.options.dev),
199
+ })
200
+ addServer(join(doorDir, "door.ts"))
201
+ }
@@ -0,0 +1,5 @@
1
+ /** `hamur dev`: the runner answers `<route>/chunks/<name>.json` and `<route>/search/<name>.json` from the dev index. */
2
+ export const DEV_ROUTE = "/_hamur/content/dev"
3
+
4
+ /** `hamur dev` re-runs the build loaders here, then the app's dev door drops the live results and answers 204. */
5
+ export const REFRESH_ROUTE = "/_hamur/content/refresh"
@@ -0,0 +1,299 @@
1
+ import { isAbsolute, relative, resolve, sep } from "node:path"
2
+ import {
3
+ addAppPlugin,
4
+ addDevServerHandler,
5
+ createResolver,
6
+ DiagnosticError,
7
+ useDevChannel,
8
+ useLogger,
9
+ type HamurContext,
10
+ } from "hamur/kit"
11
+ import type {
12
+ CollectionDefinition,
13
+ CollectionSource,
14
+ ContentConfig,
15
+ ContentEntry,
16
+ LoadedContentConfig,
17
+ SourceOptions,
18
+ } from "../types.ts"
19
+ import { parseRefreshBody } from "../runtime/refresh-body.ts"
20
+ import { DEV_ROUTE, REFRESH_ROUTE } from "./dev-route.ts"
21
+ import type { ContentIndex } from "./index.ts"
22
+ import { searchIndexOf } from "./search.ts"
23
+
24
+ export interface ContentUpdate {
25
+ collection: string
26
+ id: string
27
+ }
28
+
29
+ export interface ContentFailure {
30
+ collection: string
31
+ /** The failing file, relative to the root. */
32
+ file: string
33
+ /** The message, which names the file and the field. */
34
+ message: string
35
+ }
36
+
37
+ /** A file whose error is gone: its collection read cleanly again, with the file fixed or removed. */
38
+ export interface ContentFixed {
39
+ collection: string
40
+ file: string
41
+ }
42
+
43
+ const isInside = (file: string, dir: string): boolean => {
44
+ const path = relative(dir, file)
45
+ return path !== "" && !path.startsWith("..") && !isAbsolute(path)
46
+ }
47
+
48
+ /** The sources below `content/`; a remote source's files are not watched. */
49
+ const sourcesOf = (source: CollectionSource): SourceOptions[] =>
50
+ (Array.isArray(source) ? source : [source]).flatMap((item) =>
51
+ typeof item === "string" ? [{ include: item }] : item.repository === undefined ? [item] : [],
52
+ )
53
+
54
+ const shownOf = (rootDir: string, file: string): string => relative(rootDir, file).split(sep).join("/")
55
+
56
+ /** `file` below the source's `cwd`, when its `include` matches and no `exclude` does. */
57
+ function matchOf(
58
+ source: SourceOptions,
59
+ rootDir: string,
60
+ file: string,
61
+ ): { stem: string; extension: string } | undefined {
62
+ const cwd = resolve(rootDir, "content", source.cwd ?? "")
63
+ if (!isInside(file, cwd)) return undefined
64
+ const path = relative(cwd, file).split(sep).join("/")
65
+ if (
66
+ !new Bun.Glob(source.include).match(path) ||
67
+ (source.exclude ?? []).some((pattern) => new Bun.Glob(pattern).match(path))
68
+ )
69
+ return undefined
70
+ const dot = path.lastIndexOf(".")
71
+ const extension = dot > path.lastIndexOf("/") ? path.slice(dot + 1) : ""
72
+ return { stem: extension ? path.slice(0, dot) : path, extension }
73
+ }
74
+
75
+ /** The collections a saved file may change: those with a source that matches it, and any loader collection when it is below `content/`. */
76
+ export function collectionsOf(config: ContentConfig, rootDir: string, file: string): string[] {
77
+ const content = resolve(rootDir, "content")
78
+ return Object.entries(config.collections)
79
+ .filter(([, collection]) =>
80
+ collection.source === undefined
81
+ ? isInside(file, content)
82
+ : sourcesOf(collection.source).some((source) => matchOf(source, rootDir, file)),
83
+ )
84
+ .map(([name]) => name)
85
+ }
86
+
87
+ /** The ids of the entries `file` gives a source collection: its stem, and `<stem>/<n>` for an array file. */
88
+ export function fileIds(
89
+ collection: CollectionDefinition,
90
+ rootDir: string,
91
+ file: string,
92
+ entries: readonly ContentEntry[],
93
+ ): string[] {
94
+ if (collection.source === undefined) return []
95
+ const ids = new Set<string>()
96
+ for (const source of sourcesOf(collection.source)) {
97
+ const match = matchOf(source, rootDir, file)
98
+ if (match)
99
+ for (const entry of entries)
100
+ if (entry.stem === match.stem && entry.extension === match.extension) ids.add(entry.id)
101
+ }
102
+ return [...ids]
103
+ }
104
+
105
+ /** The ids added, removed or changed between two reads of a collection. */
106
+ export function changedIds(before: readonly ContentEntry[], after: readonly ContentEntry[]): string[] {
107
+ const old = new Map(before.map((entry) => [entry.id, JSON.stringify(entry)]))
108
+ const ids: string[] = []
109
+ for (const entry of after) {
110
+ if (old.get(entry.id) !== JSON.stringify(entry)) ids.push(entry.id)
111
+ old.delete(entry.id)
112
+ }
113
+ return [...ids, ...old.keys()]
114
+ }
115
+
116
+ export interface ContentUpdaterOptions {
117
+ config: ContentConfig
118
+ rootDir: string
119
+ index: Pick<ContentIndex, "read" | "rebuild">
120
+ update(update: ContentUpdate): void
121
+ fail(failure: ContentFailure): void
122
+ fixed(fixed: ContentFixed): void
123
+ }
124
+
125
+ export interface ContentUpdater {
126
+ /** Queues `file`; resolves when every queued file is handled, `undefined` when no collection reads it. */
127
+ changed(file: string): Promise<void> | undefined
128
+ /** Queues `names` to be read again, loaders run again; resolves when every queued collection is handled. */
129
+ refresh(names: readonly string[]): Promise<void>
130
+ /** The errors still standing, one per collection and file, for a page that loads after they were sent. */
131
+ errors(): ContentFailure[]
132
+ }
133
+
134
+ /**
135
+ * Rebuilds the collections of each saved file one at a time, so a slow parse is never overtaken by an older
136
+ * one; files saved while a rebuild runs wait and are read together in the next one.
137
+ */
138
+ export function createContentUpdater({
139
+ config,
140
+ rootDir,
141
+ index,
142
+ update,
143
+ fail,
144
+ fixed,
145
+ }: ContentUpdaterOptions): ContentUpdater {
146
+ const pending = new Map<string, Set<string>>()
147
+ const errors = new Map<string, ContentFailure>()
148
+ let running: Promise<void> | undefined
149
+ const keyOf = (collection: string, file: string) => `${collection}\0${file}`
150
+
151
+ /** The file a message names (it starts with `<file>:`) among the saved ones and those already failing; else the last saved. */
152
+ function failingFile(name: string, message: string, files: string[]): string {
153
+ const known = [
154
+ ...files.map((file) => shownOf(rootDir, file)),
155
+ ...[...errors.values()].filter((error) => error.collection === name).map((error) => error.file),
156
+ ]
157
+ const last = files.at(-1)
158
+ return (
159
+ known.find((file) => message.startsWith(`${file}:`)) ??
160
+ (last === undefined ? "content.config.ts" : shownOf(rootDir, last))
161
+ )
162
+ }
163
+
164
+ async function run(name: string, files: string[]): Promise<void> {
165
+ const before = (await index.read())[name] ?? []
166
+ let after: ContentEntry[]
167
+ try {
168
+ after = await index.rebuild(name)
169
+ } catch (error) {
170
+ const message = error instanceof Error ? error.message : String(error)
171
+ const named = error instanceof DiagnosticError ? (error.at ? `${error.at}: ${error.text}` : error.text) : message
172
+ const failure = { collection: name, file: failingFile(name, named, files), message }
173
+ errors.set(keyOf(name, failure.file), failure)
174
+ fail(failure)
175
+ return
176
+ }
177
+ for (const [key, error] of errors) {
178
+ if (error.collection !== name) continue
179
+ errors.delete(key)
180
+ fixed({ collection: name, file: error.file })
181
+ }
182
+ const ids = new Set(changedIds(before, after))
183
+ for (const file of files) for (const id of fileIds(config.collections[name]!, rootDir, file, after)) ids.add(id)
184
+ for (const id of ids) update({ collection: name, id })
185
+ }
186
+
187
+ async function drain(): Promise<void> {
188
+ try {
189
+ for (let next = pending.entries().next(); !next.done; next = pending.entries().next()) {
190
+ const [name, files] = next.value
191
+ pending.delete(name)
192
+ await run(name, [...files])
193
+ }
194
+ } finally {
195
+ running = undefined
196
+ }
197
+ }
198
+
199
+ return {
200
+ errors: () => [...errors.values()],
201
+ changed(file) {
202
+ const names = collectionsOf(config, rootDir, file)
203
+ if (!names.length) return undefined
204
+ for (const name of names) pending.set(name, (pending.get(name) ?? new Set()).add(file))
205
+ return (running ??= drain())
206
+ },
207
+ refresh(names) {
208
+ if (!names.length) return Promise.resolve()
209
+ for (const name of names) if (!pending.has(name)) pending.set(name, new Set())
210
+ return (running ??= drain())
211
+ },
212
+ }
213
+ }
214
+
215
+ /** Under `hamur dev`, a saved content file updates the dev index and the pages that read it. */
216
+ export function setupDev(
217
+ hamur: HamurContext,
218
+ config: LoadedContentConfig,
219
+ index: ContentIndex,
220
+ search: readonly string[],
221
+ ): void {
222
+ if (!hamur.options.dev) return
223
+ const { rootDir } = hamur.options
224
+ const logger = useLogger("content")
225
+ const channel = useDevChannel()
226
+ const updater = createContentUpdater({
227
+ config,
228
+ rootDir,
229
+ index,
230
+ update: (update) => channel.send("content:update", update),
231
+ fail: (failure) => {
232
+ logger.error(failure.message)
233
+ channel.send("content:error", failure)
234
+ },
235
+ fixed: (fixed) => channel.send("content:fixed", fixed),
236
+ })
237
+
238
+ addDevServerHandler({
239
+ route: DEV_ROUTE,
240
+ handler: async (request) => {
241
+ const pathname = new URL(request.url).pathname
242
+ if (pathname.endsWith(`${DEV_ROUTE}/errors.json`))
243
+ return Response.json(updater.errors(), { headers: { "cache-control": "no-store" } })
244
+ const match = /\/(chunks|search)\/([^/]+)\.json$/.exec(pathname)
245
+ if (!match) return undefined
246
+ const kind = match[1]
247
+ const name = match[2]!
248
+ const collection = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined
249
+ if (!collection || collection.expose === false || (kind === "search" && !search.includes(name))) return undefined
250
+ const entries = (await index.read())[name]!
251
+ return Response.json(kind === "chunks" ? entries : searchIndexOf(entries), {
252
+ headers: { "cache-control": "no-store" },
253
+ })
254
+ },
255
+ })
256
+ addDevServerHandler({
257
+ route: REFRESH_ROUTE,
258
+ handler: async (request) => {
259
+ if (request.method !== "POST" || !new URL(request.url).pathname.endsWith(REFRESH_ROUTE)) return undefined
260
+ let requested: string[] | undefined
261
+ try {
262
+ requested = parseRefreshBody(await request.text()).collections
263
+ } catch {
264
+ return undefined
265
+ }
266
+ if (requested?.some((name) => !Object.hasOwn(config.collections, name) && !Object.hasOwn(config.live, name)))
267
+ return undefined
268
+ await updater.refresh(
269
+ (requested ?? Object.keys(config.collections)).filter((name) => Object.hasOwn(config.collections, name)),
270
+ )
271
+ return undefined
272
+ },
273
+ })
274
+ addAppPlugin({ src: createResolver(import.meta.url).resolve("../runtime/dev-plugin.ts"), mode: "client" })
275
+
276
+ hamur.hooks.hook("dev:change", async (change) => {
277
+ if (!collectionsOf(config, rootDir, change.file).length) return
278
+ if (
279
+ await index.read().then(
280
+ () => false,
281
+ () => true,
282
+ )
283
+ ) {
284
+ index.reset()
285
+ try {
286
+ await index.read()
287
+ } catch (error) {
288
+ logger.error(error instanceof Error ? error.message : String(error))
289
+ return
290
+ }
291
+ change.rebuildServer = true
292
+ change.reload = true
293
+ return
294
+ }
295
+ updater
296
+ .changed(change.file)
297
+ ?.catch((error: unknown) => logger.error(error instanceof Error ? error.message : String(error)))
298
+ })
299
+ }