@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.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/chunks/bun-render-65mwzeq2.js +58 -0
- package/dist/chunks/bun-render-7jxnxg3v.js +714 -0
- package/dist/chunks/bun-render-mxhn5twt.js +130 -0
- package/dist/chunks/bun-render-w7fh3fg7.js +36 -0
- package/dist/src/adapters/html.js +134 -0
- package/dist/src/adapters/preact.js +126 -0
- package/dist/src/adapters/react.js +116 -0
- package/dist/src/adapters/solid.js +153 -0
- package/dist/src/adapters/svelte.js +90 -0
- package/dist/src/adapters/vue.js +166 -0
- package/dist/src/index.js +2732 -0
- package/dist/src/query.js +97 -0
- package/dist/src/render.js +12 -0
- package/dist/src/server/index.js +349 -0
- package/dist/types/src/adapters/html.d.ts +54 -0
- package/dist/types/src/adapters/page.d.ts +21 -0
- package/dist/types/src/adapters/preact.d.ts +53 -0
- package/dist/types/src/adapters/prose.d.ts +21 -0
- package/dist/types/src/adapters/react.d.ts +53 -0
- package/dist/types/src/adapters/search.d.ts +12 -0
- package/dist/types/src/adapters/solid.d.ts +54 -0
- package/dist/types/src/adapters/svelte-page.d.ts +9 -0
- package/dist/types/src/adapters/svelte-search.d.ts +9 -0
- package/dist/types/src/adapters/svelte.d.ts +24 -0
- package/dist/types/src/adapters/vue.d.ts +189 -0
- package/dist/types/src/build/api.d.ts +24 -0
- package/dist/types/src/build/dev-route.d.ts +4 -0
- package/dist/types/src/build/dev.d.ts +48 -0
- package/dist/types/src/build/graphql.d.ts +10 -0
- package/dist/types/src/build/image.d.ts +16 -0
- package/dist/types/src/build/index.d.ts +76 -0
- package/dist/types/src/build/live.d.ts +6 -0
- package/dist/types/src/build/prerender.d.ts +8 -0
- package/dist/types/src/build/query.d.ts +10 -0
- package/dist/types/src/build/raw.d.ts +23 -0
- package/dist/types/src/build/search.d.ts +9 -0
- package/dist/types/src/build/types.d.ts +16 -0
- package/dist/types/src/component.d.ts +10 -0
- package/dist/types/src/config.d.ts +6 -0
- package/dist/types/src/define.d.ts +14 -0
- package/dist/types/src/error.d.ts +4 -0
- package/dist/types/src/image.d.ts +15 -0
- package/dist/types/src/index.d.ts +64 -0
- package/dist/types/src/loaders/data.d.ts +12 -0
- package/dist/types/src/loaders/file.d.ts +3 -0
- package/dist/types/src/loaders/git.d.ts +27 -0
- package/dist/types/src/loaders/glob.d.ts +14 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/query.d.ts +17 -0
- package/dist/types/src/render.d.ts +9 -0
- package/dist/types/src/runtime/client.d.ts +25 -0
- package/dist/types/src/runtime/dev-client.d.ts +4 -0
- package/dist/types/src/runtime/dev-plugin.d.ts +12 -0
- package/dist/types/src/runtime/dev-store.d.ts +5 -0
- package/dist/types/src/runtime/live.d.ts +36 -0
- package/dist/types/src/runtime/navigation.d.ts +35 -0
- package/dist/types/src/runtime/page-plugin.d.ts +2 -0
- package/dist/types/src/runtime/page-source.d.ts +12 -0
- package/dist/types/src/runtime/query.d.ts +100 -0
- package/dist/types/src/runtime/raw-path.d.ts +2 -0
- package/dist/types/src/runtime/refresh-body.d.ts +4 -0
- package/dist/types/src/runtime/search-loaders.d.ts +7 -0
- package/dist/types/src/runtime/search-plugin.d.ts +2 -0
- package/dist/types/src/runtime/search-store.d.ts +19 -0
- package/dist/types/src/runtime/search.d.ts +28 -0
- package/dist/types/src/runtime/sections.d.ts +36 -0
- package/dist/types/src/runtime/server-store.d.ts +4 -0
- package/dist/types/src/runtime/store.d.ts +31 -0
- package/dist/types/src/server/door-dev-static.d.ts +3 -0
- package/dist/types/src/server/door-dev.d.ts +4 -0
- package/dist/types/src/server/door-static.d.ts +2 -0
- package/dist/types/src/server/door.d.ts +3 -0
- package/dist/types/src/server/endpoint.d.ts +1 -0
- package/dist/types/src/server/graphql.d.ts +24 -0
- package/dist/types/src/server/index.d.ts +10 -0
- package/dist/types/src/server/install.d.ts +1 -0
- package/dist/types/src/server/live.d.ts +10 -0
- package/dist/types/src/server/query.d.ts +15 -0
- package/dist/types/src/server/refresh.d.ts +2 -0
- package/dist/types/src/server/rest.d.ts +62 -0
- package/dist/types/src/server/search.d.ts +5 -0
- package/dist/types/src/server-config.d.ts +12 -0
- package/dist/types/src/source.d.ts +24 -0
- package/dist/types/src/types.d.ts +293 -0
- package/package.json +110 -4
- package/src/adapters/ContentRenderer.svelte +27 -0
- package/src/adapters/ProseA.svelte +11 -0
- package/src/adapters/ProseBlockquote.svelte +7 -0
- package/src/adapters/ProseCode.svelte +7 -0
- package/src/adapters/ProseEm.svelte +7 -0
- package/src/adapters/ProseH1.svelte +7 -0
- package/src/adapters/ProseH2.svelte +7 -0
- package/src/adapters/ProseH3.svelte +7 -0
- package/src/adapters/ProseH4.svelte +7 -0
- package/src/adapters/ProseH5.svelte +7 -0
- package/src/adapters/ProseH6.svelte +7 -0
- package/src/adapters/ProseHr.svelte +5 -0
- package/src/adapters/ProseImg.svelte +5 -0
- package/src/adapters/ProseLi.svelte +7 -0
- package/src/adapters/ProseOl.svelte +7 -0
- package/src/adapters/ProseP.svelte +7 -0
- package/src/adapters/ProsePre.svelte +21 -0
- package/src/adapters/ProseStrong.svelte +7 -0
- package/src/adapters/ProseTable.svelte +7 -0
- package/src/adapters/ProseUl.svelte +7 -0
- package/src/adapters/html.ts +152 -0
- package/src/adapters/page.ts +52 -0
- package/src/adapters/preact.ts +154 -0
- package/src/adapters/prose.ts +55 -0
- package/src/adapters/react.ts +142 -0
- package/src/adapters/search.ts +32 -0
- package/src/adapters/solid.ts +183 -0
- package/src/adapters/svelte-defaults.ts +41 -0
- package/src/adapters/svelte-page.ts +29 -0
- package/src/adapters/svelte-search.ts +36 -0
- package/src/adapters/svelte.ts +30 -0
- package/src/adapters/test/OwnA.svelte +7 -0
- package/src/adapters/test/OwnH1.svelte +7 -0
- package/src/adapters/test/OwnPre.svelte +7 -0
- package/src/adapters/test/support.ts +106 -0
- package/src/adapters/vue.ts +182 -0
- package/src/build/api.ts +201 -0
- package/src/build/dev-route.ts +5 -0
- package/src/build/dev.ts +299 -0
- package/src/build/graphql.ts +197 -0
- package/src/build/image.ts +60 -0
- package/src/build/index.ts +597 -0
- package/src/build/live.ts +34 -0
- package/src/build/prerender.ts +34 -0
- package/src/build/query.ts +70 -0
- package/src/build/raw.ts +157 -0
- package/src/build/search.ts +64 -0
- package/src/build/types.ts +108 -0
- package/src/component.ts +86 -0
- package/src/config.ts +156 -0
- package/src/define.ts +33 -0
- package/src/env.d.ts +34 -0
- package/src/error.ts +4 -0
- package/src/image.ts +41 -0
- package/src/index.ts +103 -0
- package/src/loaders/data.ts +186 -0
- package/src/loaders/file.ts +53 -0
- package/src/loaders/git.ts +266 -0
- package/src/loaders/glob.ts +179 -0
- package/src/module.ts +26 -0
- package/src/query.ts +82 -0
- package/src/render.ts +16 -0
- package/src/runtime/client.ts +75 -0
- package/src/runtime/dev-client.ts +6 -0
- package/src/runtime/dev-plugin.ts +64 -0
- package/src/runtime/dev-store.ts +19 -0
- package/src/runtime/live.ts +331 -0
- package/src/runtime/navigation.ts +225 -0
- package/src/runtime/page-plugin.ts +13 -0
- package/src/runtime/page-source.ts +22 -0
- package/src/runtime/query.ts +605 -0
- package/src/runtime/raw-path.ts +2 -0
- package/src/runtime/refresh-body.ts +22 -0
- package/src/runtime/search-loaders.ts +14 -0
- package/src/runtime/search-plugin.ts +6 -0
- package/src/runtime/search-store.ts +73 -0
- package/src/runtime/search.ts +126 -0
- package/src/runtime/sections.ts +155 -0
- package/src/runtime/server-store.ts +12 -0
- package/src/runtime/store.ts +59 -0
- package/src/server/door-dev-static.ts +6 -0
- package/src/server/door-dev.ts +7 -0
- package/src/server/door-static.ts +4 -0
- package/src/server/door.ts +6 -0
- package/src/server/endpoint.ts +17 -0
- package/src/server/graphql.ts +59 -0
- package/src/server/index.ts +17 -0
- package/src/server/install.ts +6 -0
- package/src/server/live.ts +51 -0
- package/src/server/query.ts +46 -0
- package/src/server/refresh.ts +19 -0
- package/src/server/rest.ts +157 -0
- package/src/server/search.ts +22 -0
- package/src/server-config.ts +24 -0
- package/src/source.ts +99 -0
- package/src/types.ts +282 -0
package/src/build/api.ts
ADDED
|
@@ -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"
|
package/src/build/dev.ts
ADDED
|
@@ -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
|
+
}
|