@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.
- 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 +140 -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
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { HamurDevEvents } from "hamur"
|
|
2
|
+
import { $fetch, definePlugin, onDevEvent, refreshData, type AppContext } from "hamur/app"
|
|
3
|
+
import { DEV_ROUTE } from "../build/dev-route.ts"
|
|
4
|
+
import { forgetSearch } from "../adapters/search.ts"
|
|
5
|
+
import { forgetChunk } from "./client.ts"
|
|
6
|
+
|
|
7
|
+
/** An async-data key holds a collection when the name is one of its words: `blog`, `blog:/hello`, `blog-post`. */
|
|
8
|
+
export const holdsCollection = (key: string, name: string): boolean => key.split(/[^A-Za-z0-9]+/).includes(name)
|
|
9
|
+
|
|
10
|
+
/** Re-runs the loads that queried one of `names` (each records `content:<name>`), and refreshes the mounted async-data entries whose key holds one, as `router.refresh()` does for each. */
|
|
11
|
+
export function refreshCollections(
|
|
12
|
+
app: AppContext,
|
|
13
|
+
names: readonly string[],
|
|
14
|
+
refresh: typeof refreshData = refreshData,
|
|
15
|
+
): void {
|
|
16
|
+
void refresh(names.map((name) => `content:${name}`))
|
|
17
|
+
for (const key of app.asyncData.hookedKeys())
|
|
18
|
+
if (names.some((name) => holdsCollection(key, name))) void app.asyncData.refreshHook(key)?.()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Failure = HamurDevEvents["content:error"]
|
|
22
|
+
|
|
23
|
+
/** The overlay error of a content failure: its message names the file and the field, and no stack frame applies. */
|
|
24
|
+
function failureError(failure: Failure): Error {
|
|
25
|
+
const error = new Error(failure.message)
|
|
26
|
+
error.name = "ContentError"
|
|
27
|
+
error.stack = ""
|
|
28
|
+
return error
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `hamur dev`: `content:update` drops the collection's chunk and search index and refreshes its loads and
|
|
33
|
+
* async data; `content:error` opens the overlay, and `content:fixed` of a file the page showed reloads it. The errors
|
|
34
|
+
* still standing are read once at start, so a reload with a file still broken shows the overlay again.
|
|
35
|
+
*/
|
|
36
|
+
export default definePlugin((app) => {
|
|
37
|
+
const failed = new Set<string>()
|
|
38
|
+
const keyOf = (failure: { collection: string; file: string }) => `${failure.collection}\0${failure.file}`
|
|
39
|
+
const show = (failure: Failure) => {
|
|
40
|
+
failed.add(keyOf(failure))
|
|
41
|
+
reportError(failureError(failure))
|
|
42
|
+
}
|
|
43
|
+
const changed = new Set<string>()
|
|
44
|
+
onDevEvent("content:update", ({ collection }) => {
|
|
45
|
+
forgetChunk(collection)
|
|
46
|
+
forgetSearch(collection)
|
|
47
|
+
// One save can change several entries; their events arrive one after another and refresh once.
|
|
48
|
+
if (!changed.size)
|
|
49
|
+
setTimeout(() => {
|
|
50
|
+
const names = [...changed]
|
|
51
|
+
changed.clear()
|
|
52
|
+
refreshCollections(app, names)
|
|
53
|
+
})
|
|
54
|
+
changed.add(collection)
|
|
55
|
+
})
|
|
56
|
+
onDevEvent("content:error", show)
|
|
57
|
+
onDevEvent("content:fixed", (fixed) => {
|
|
58
|
+
if (failed.delete(keyOf(fixed))) location.reload()
|
|
59
|
+
})
|
|
60
|
+
$fetch<Failure[]>(`${DEV_ROUTE}/errors.json`, { retry: 0 }).then(
|
|
61
|
+
(failures) => failures.forEach(show),
|
|
62
|
+
() => {},
|
|
63
|
+
)
|
|
64
|
+
})
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises"
|
|
2
|
+
import type { ContentEntry } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
/** `hamur dev`: a collection's entries read from the file the dev index writes, again only after the file changed. */
|
|
5
|
+
export function devChunk(file: string): () => Promise<{ default: ContentEntry[] }> {
|
|
6
|
+
let last: { version: string; entries: Promise<ContentEntry[]> } | undefined
|
|
7
|
+
return async () => {
|
|
8
|
+
const info = await stat(file)
|
|
9
|
+
const version = `${info.mtimeMs}:${info.size}:${info.ino}`
|
|
10
|
+
if (last?.version !== version) {
|
|
11
|
+
const entries = readFile(file, "utf8").then((text) => JSON.parse(text) as ContentEntry[])
|
|
12
|
+
last = { version, entries }
|
|
13
|
+
entries.catch(() => {
|
|
14
|
+
if (last?.entries === entries) last = undefined
|
|
15
|
+
})
|
|
16
|
+
}
|
|
17
|
+
return { default: await last.entries }
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import type { MdRoot } from "hamur/markdown"
|
|
2
|
+
import type { StandardSchemaV1 } from "hamur/server"
|
|
3
|
+
import type { CacheHint, LiveCollectionDefinition, LiveCollectionResult, LiveEntry, LiveEntryResult } from "../types.ts"
|
|
4
|
+
|
|
5
|
+
/** The part of a `useStorage` mount live results are kept in. */
|
|
6
|
+
export interface LiveStorage {
|
|
7
|
+
getItem(key: string): Promise<unknown>
|
|
8
|
+
setItem(key: string, value: unknown, options?: { ttl?: number }): Promise<void>
|
|
9
|
+
removeItem(key: string): Promise<void>
|
|
10
|
+
clear(prefix: string): Promise<void>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface LiveContentOptions {
|
|
14
|
+
/** The live collections of `content.config.ts`. */
|
|
15
|
+
collections: Record<string, LiveCollectionDefinition>
|
|
16
|
+
/** Every collection name of `content.config.ts`, live or not. */
|
|
17
|
+
names: readonly string[]
|
|
18
|
+
storage(): LiveStorage
|
|
19
|
+
/** Parses a Markdown body; absent where `Bun.markdown` is not. */
|
|
20
|
+
parseMarkdown?: (source: string) => Promise<MdRoot>
|
|
21
|
+
/** Told once per process when the cache cannot be read or written; the result is then loaded, or not kept. */
|
|
22
|
+
warn?: (message: string) => void
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface LiveContent {
|
|
26
|
+
getLiveCollection(name: string, filter?: unknown): Promise<LiveCollectionResult>
|
|
27
|
+
getLiveEntry(name: string, filter: unknown): Promise<LiveEntryResult>
|
|
28
|
+
refreshContent(options?: { collections?: string[] }): Promise<void>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** An error whose message is already the one the caller gets. */
|
|
32
|
+
class LiveError extends Error {}
|
|
33
|
+
|
|
34
|
+
type Fields = Record<string, unknown>
|
|
35
|
+
|
|
36
|
+
const isObject = (value: unknown): value is Fields =>
|
|
37
|
+
value !== null && typeof value === "object" && !Array.isArray(value)
|
|
38
|
+
|
|
39
|
+
const isPlain = (value: unknown): value is Fields =>
|
|
40
|
+
isObject(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
|
|
41
|
+
|
|
42
|
+
const pathOf = (path: StandardSchemaV1.Issue["path"]): string =>
|
|
43
|
+
(path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".")
|
|
44
|
+
|
|
45
|
+
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
|
|
46
|
+
|
|
47
|
+
const kindOf = (value: unknown): string => {
|
|
48
|
+
if (typeof value === "number") return String(value)
|
|
49
|
+
if (typeof value !== "object" || value === null) return typeof value
|
|
50
|
+
return (value as object).constructor?.name ?? "object"
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The filter as JSON with sorted object keys, so `{ a, b }` and `{ b, a }` share a cache key; an object key whose value is
|
|
55
|
+
* `undefined` is left out, as JSON does, so it equals an absent key. Anything JSON would change or drop is refused.
|
|
56
|
+
*/
|
|
57
|
+
function stable(value: unknown, path: string, seen: Set<object>): string {
|
|
58
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value)
|
|
59
|
+
if (typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value)
|
|
60
|
+
if (typeof value === "object" && (Array.isArray(value) || isPlain(value))) {
|
|
61
|
+
if (seen.has(value)) throw new TypeError(`the filter must be plain JSON (${path} refers to itself)`)
|
|
62
|
+
seen.add(value)
|
|
63
|
+
let text: string
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
text = `[${value.map((item, index) => (item === undefined ? refuse(item, `${path}[${index}]`) : stable(item, `${path}[${index}]`, seen))).join(",")}]`
|
|
66
|
+
} else {
|
|
67
|
+
const keys = Object.keys(value)
|
|
68
|
+
.filter((key) => value[key] !== undefined)
|
|
69
|
+
.sort()
|
|
70
|
+
text = `{${keys.map((key) => `${JSON.stringify(key)}:${stable(value[key], `${path}.${key}`, seen)}`).join(",")}}`
|
|
71
|
+
}
|
|
72
|
+
seen.delete(value)
|
|
73
|
+
return text
|
|
74
|
+
}
|
|
75
|
+
return refuse(value, path)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function refuse(value: unknown, path: string): never {
|
|
79
|
+
throw new TypeError(`the filter must be plain JSON (got ${kindOf(value)} at ${path})`)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function hashOf(text: string): Promise<string> {
|
|
83
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))
|
|
84
|
+
return Array.from(digest.subarray(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const liveKeyPrefix = (collection: string): string => `content:live:${collection}`
|
|
88
|
+
|
|
89
|
+
/** `content:live:<collection>:<hash of the call and its filter>`; an `undefined` filter is no filter. */
|
|
90
|
+
export async function liveKey(collection: string, kind: "collection" | "entry", filter: unknown): Promise<string> {
|
|
91
|
+
return `${liveKeyPrefix(collection)}:${await hashOf(`${kind}\0${filter === undefined ? "" : stable(filter, "filter", new Set())}`)}`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function hintOf(value: unknown): CacheHint {
|
|
95
|
+
if (!isObject(value)) return {}
|
|
96
|
+
const hint: CacheHint = {}
|
|
97
|
+
if (Array.isArray(value.tags)) hint.tags = value.tags.filter((tag): tag is string => typeof tag === "string")
|
|
98
|
+
if (typeof value.maxAge === "number" && Number.isFinite(value.maxAge) && value.maxAge >= 0) hint.maxAge = value.maxAge
|
|
99
|
+
const modified =
|
|
100
|
+
value.lastModified instanceof Date
|
|
101
|
+
? value.lastModified
|
|
102
|
+
: typeof value.lastModified === "string" || typeof value.lastModified === "number"
|
|
103
|
+
? new Date(value.lastModified)
|
|
104
|
+
: undefined
|
|
105
|
+
if (modified && !Number.isNaN(modified.getTime())) hint.lastModified = modified
|
|
106
|
+
return hint
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The tags of every hint, the shortest `maxAge` and the latest `lastModified`. */
|
|
110
|
+
export function mergeHints(hints: readonly (CacheHint | undefined)[]): CacheHint {
|
|
111
|
+
const merged: CacheHint = {}
|
|
112
|
+
const tags = new Set<string>()
|
|
113
|
+
for (const hint of hints) {
|
|
114
|
+
if (!hint) continue
|
|
115
|
+
for (const tag of hint.tags ?? []) tags.add(tag)
|
|
116
|
+
if (hint.maxAge !== undefined) merged.maxAge = Math.min(merged.maxAge ?? Infinity, hint.maxAge)
|
|
117
|
+
if (hint.lastModified && (!merged.lastModified || hint.lastModified > merged.lastModified))
|
|
118
|
+
merged.lastModified = hint.lastModified
|
|
119
|
+
}
|
|
120
|
+
if (tags.size) merged.tags = [...tags]
|
|
121
|
+
return merged
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The live collections' request-time reads and their cache. */
|
|
125
|
+
export function createLiveContent({
|
|
126
|
+
collections,
|
|
127
|
+
names,
|
|
128
|
+
storage,
|
|
129
|
+
parseMarkdown,
|
|
130
|
+
warn = () => {},
|
|
131
|
+
}: LiveContentOptions): LiveContent {
|
|
132
|
+
/** Bumped by each refresh of a collection: a load that started before it never stores its result. */
|
|
133
|
+
const generations = new Map<string, number>()
|
|
134
|
+
const refreshing = new Map<string, Promise<void>>()
|
|
135
|
+
const generationOf = (name: string): number => generations.get(name) ?? 0
|
|
136
|
+
let warned = false
|
|
137
|
+
const cacheFailed = (doing: string, error: unknown): void => {
|
|
138
|
+
if (warned) return
|
|
139
|
+
warned = true
|
|
140
|
+
warn(`content: live results are not cached: ${doing} the cache storage failed: ${messageOf(error)}`)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function definitionOf(call: string, name: string): LiveCollectionDefinition {
|
|
144
|
+
if (typeof name !== "string" || !Object.hasOwn(collections, name))
|
|
145
|
+
throw new TypeError(`${call}: ${JSON.stringify(name)} is not a live collection of content.config.ts`)
|
|
146
|
+
return collections[name]!
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function entryOf(call: string, definition: LiveCollectionDefinition, raw: unknown): Promise<LiveEntry> {
|
|
150
|
+
if (!isObject(raw) || typeof raw.id !== "string" || !isObject(raw.data))
|
|
151
|
+
throw new LiveError(`${call}: an entry must be { id: string, data: object }`)
|
|
152
|
+
const where = `${call}: entry ${JSON.stringify(raw.id)}`
|
|
153
|
+
let data: unknown = raw.data
|
|
154
|
+
if (definition.schema) {
|
|
155
|
+
let result: StandardSchemaV1.Result<unknown>
|
|
156
|
+
try {
|
|
157
|
+
result = await definition.schema["~standard"].validate(data)
|
|
158
|
+
} catch (error) {
|
|
159
|
+
throw new LiveError(`${where}: ${messageOf(error)}`, { cause: error })
|
|
160
|
+
}
|
|
161
|
+
if (result.issues)
|
|
162
|
+
throw new LiveError(
|
|
163
|
+
result.issues
|
|
164
|
+
.map((issue) => `${where}: ${pathOf(issue.path) ? `${pathOf(issue.path)}: ` : ""}${issue.message}`)
|
|
165
|
+
.join("\n"),
|
|
166
|
+
{ cause: result.issues },
|
|
167
|
+
)
|
|
168
|
+
data = result.value
|
|
169
|
+
}
|
|
170
|
+
if (!isObject(data)) throw new LiveError(`${where}: a schema output must be an object`)
|
|
171
|
+
let json: Fields
|
|
172
|
+
try {
|
|
173
|
+
json = JSON.parse(JSON.stringify(data)) as Fields
|
|
174
|
+
} catch (error) {
|
|
175
|
+
throw new LiveError(`${where}: data must be JSON (${messageOf(error)})`, { cause: error })
|
|
176
|
+
}
|
|
177
|
+
const entry: LiveEntry = { id: raw.id, data: json }
|
|
178
|
+
if (typeof raw.body === "string") {
|
|
179
|
+
if (!parseMarkdown)
|
|
180
|
+
throw new LiveError(
|
|
181
|
+
`${where} has a Markdown body, which only the bun preset parses at run time; return a Markdown AST`,
|
|
182
|
+
)
|
|
183
|
+
try {
|
|
184
|
+
entry.body = await parseMarkdown(raw.body)
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw new LiveError(`${where}: ${messageOf(error)}`, { cause: error })
|
|
187
|
+
}
|
|
188
|
+
} else if (raw.body !== undefined) entry.body = raw.body as MdRoot
|
|
189
|
+
if (raw.cacheHint !== undefined) entry.cacheHint = hintOf(raw.cacheHint)
|
|
190
|
+
return entry
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const failed = (call: string, definition: LiveCollectionDefinition, error: unknown): Error =>
|
|
194
|
+
error instanceof LiveError
|
|
195
|
+
? error
|
|
196
|
+
: new Error(
|
|
197
|
+
`${call}: ${definition.loader.name ? `loader ${JSON.stringify(definition.loader.name)}` : "loader"} failed: ${messageOf(error)}`,
|
|
198
|
+
{ cause: error },
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
function revive<T extends { cacheHint: CacheHint }>(value: T, entries: (value: T) => LiveEntry[]): T {
|
|
202
|
+
value.cacheHint = hintOf(value.cacheHint)
|
|
203
|
+
for (const entry of entries(value)) if (entry.cacheHint !== undefined) entry.cacheHint = hintOf(entry.cacheHint)
|
|
204
|
+
return value
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
interface Read<T> {
|
|
208
|
+
call: string
|
|
209
|
+
name: string
|
|
210
|
+
kind: "collection" | "entry"
|
|
211
|
+
filter: unknown
|
|
212
|
+
load(): Promise<T>
|
|
213
|
+
entries(value: T): LiveEntry[]
|
|
214
|
+
fail(error: Error): T
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A failing cache read or write is a miss, never the caller's error; only the filter and the loader give `error`. */
|
|
218
|
+
async function cached<T extends { error: Error | undefined; cacheHint: CacheHint }>({
|
|
219
|
+
call,
|
|
220
|
+
name,
|
|
221
|
+
kind,
|
|
222
|
+
filter,
|
|
223
|
+
load,
|
|
224
|
+
entries,
|
|
225
|
+
fail,
|
|
226
|
+
}: Read<T>): Promise<T> {
|
|
227
|
+
let key: string
|
|
228
|
+
try {
|
|
229
|
+
key = await liveKey(name, kind, filter)
|
|
230
|
+
} catch (error) {
|
|
231
|
+
return fail(new Error(`${call}: ${messageOf(error)}`, { cause: error }))
|
|
232
|
+
}
|
|
233
|
+
await refreshing.get(name)?.catch(() => {})
|
|
234
|
+
try {
|
|
235
|
+
const hit = await storage().getItem(key)
|
|
236
|
+
if (isObject(hit)) return revive({ ...hit, error: undefined } as unknown as T, entries)
|
|
237
|
+
} catch (error) {
|
|
238
|
+
cacheFailed("reading", error)
|
|
239
|
+
}
|
|
240
|
+
const generation = generationOf(name)
|
|
241
|
+
const result = await load()
|
|
242
|
+
const { maxAge } = result.cacheHint
|
|
243
|
+
if (result.error !== undefined || maxAge === undefined || !(maxAge > 0) || generation !== generationOf(name))
|
|
244
|
+
return result
|
|
245
|
+
try {
|
|
246
|
+
const store = storage()
|
|
247
|
+
await store.setItem(key, result, { ttl: maxAge })
|
|
248
|
+
// A refresh whose clear ran while this write was on its way: the write landed after it.
|
|
249
|
+
if (generation !== generationOf(name)) await store.removeItem(key)
|
|
250
|
+
} catch (error) {
|
|
251
|
+
cacheFailed("writing", error)
|
|
252
|
+
}
|
|
253
|
+
return result
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return {
|
|
257
|
+
async getLiveCollection(name, filter) {
|
|
258
|
+
const call = `getLiveCollection(${JSON.stringify(name)})`
|
|
259
|
+
const definition = definitionOf(call, name)
|
|
260
|
+
return cached<LiveCollectionResult>({
|
|
261
|
+
call,
|
|
262
|
+
name,
|
|
263
|
+
kind: "collection",
|
|
264
|
+
filter,
|
|
265
|
+
async load() {
|
|
266
|
+
try {
|
|
267
|
+
const loaded: unknown = await definition.loader.loadCollection(filter)
|
|
268
|
+
if (!isObject(loaded) || !Array.isArray(loaded.entries))
|
|
269
|
+
throw new LiveError(`${call}: loadCollection must return { entries: [...] }`)
|
|
270
|
+
const entries: LiveEntry[] = []
|
|
271
|
+
for (const raw of loaded.entries) entries.push(await entryOf(call, definition, raw))
|
|
272
|
+
return {
|
|
273
|
+
entries,
|
|
274
|
+
error: undefined,
|
|
275
|
+
cacheHint: mergeHints([hintOf(loaded.cacheHint), ...entries.map((entry) => entry.cacheHint)]),
|
|
276
|
+
}
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return { entries: undefined, error: failed(call, definition, error), cacheHint: {} }
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
entries: (value) => value.entries ?? [],
|
|
282
|
+
fail: (error) => ({ entries: undefined, error, cacheHint: {} }),
|
|
283
|
+
})
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
async getLiveEntry(name, filter) {
|
|
287
|
+
const call = `getLiveEntry(${JSON.stringify(name)})`
|
|
288
|
+
const definition = definitionOf(call, name)
|
|
289
|
+
return cached<LiveEntryResult>({
|
|
290
|
+
call,
|
|
291
|
+
name,
|
|
292
|
+
kind: "entry",
|
|
293
|
+
filter,
|
|
294
|
+
async load() {
|
|
295
|
+
try {
|
|
296
|
+
const loaded: unknown = await definition.loader.loadEntry(filter)
|
|
297
|
+
if (loaded === undefined || loaded === null) return { entry: undefined, error: undefined, cacheHint: {} }
|
|
298
|
+
const entry = await entryOf(call, definition, loaded)
|
|
299
|
+
return { entry, error: undefined, cacheHint: mergeHints([entry.cacheHint]) }
|
|
300
|
+
} catch (error) {
|
|
301
|
+
return { entry: undefined, error: failed(call, definition, error), cacheHint: {} }
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
entries: (value) => (value.entry ? [value.entry] : []),
|
|
305
|
+
fail: (error) => ({ entry: undefined, error, cacheHint: {} }),
|
|
306
|
+
})
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
async refreshContent(options = {}) {
|
|
310
|
+
const requested = options.collections
|
|
311
|
+
if (requested !== undefined && !(Array.isArray(requested) && requested.every((name) => typeof name === "string")))
|
|
312
|
+
throw new TypeError("refreshContent: collections must be an array of collection names")
|
|
313
|
+
for (const name of requested ?? [])
|
|
314
|
+
if (!names.includes(name))
|
|
315
|
+
throw new TypeError(`refreshContent: ${JSON.stringify(name)} is not a collection of content.config.ts`)
|
|
316
|
+
const live = (requested ?? Object.keys(collections)).filter((name) => Object.hasOwn(collections, name))
|
|
317
|
+
await Promise.all(
|
|
318
|
+
live.map((name) => {
|
|
319
|
+
generations.set(name, generationOf(name) + 1)
|
|
320
|
+
const done: Promise<void> = Promise.resolve()
|
|
321
|
+
.then(() => storage().clear(liveKeyPrefix(name)))
|
|
322
|
+
.finally(() => {
|
|
323
|
+
if (refreshing.get(name) === done) refreshing.delete(name)
|
|
324
|
+
})
|
|
325
|
+
refreshing.set(name, done)
|
|
326
|
+
return done
|
|
327
|
+
}),
|
|
328
|
+
)
|
|
329
|
+
},
|
|
330
|
+
}
|
|
331
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { QueryError, type CollectionQueryBuilder, type QueryResult } from "./query.ts"
|
|
2
|
+
import type { ContentEntry } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
/** One node of the tree `queryCollectionNavigation` returns. */
|
|
5
|
+
export interface NavigationItem {
|
|
6
|
+
title: string
|
|
7
|
+
path: string
|
|
8
|
+
stem: string
|
|
9
|
+
icon?: string
|
|
10
|
+
children?: NavigationItem[]
|
|
11
|
+
[field: string]: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type Row = Record<string, unknown>
|
|
15
|
+
|
|
16
|
+
interface TreeNode {
|
|
17
|
+
segment: string
|
|
18
|
+
stem: string
|
|
19
|
+
index?: Row
|
|
20
|
+
pages: Array<{ segment: string; row: Row }>
|
|
21
|
+
dirs: Map<string, TreeNode>
|
|
22
|
+
rows: Row[]
|
|
23
|
+
data?: Row
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const PREFIX = /^(\d+)\./
|
|
27
|
+
const BASE_KEYS = new Set(["title", "path", "stem", "icon", "children"])
|
|
28
|
+
|
|
29
|
+
const isRecord = (value: unknown): value is Row => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
30
|
+
const strip = (segment: string): string => segment.replace(PREFIX, "")
|
|
31
|
+
|
|
32
|
+
function humanize(segment: string): string {
|
|
33
|
+
const text = strip(segment).replace(/-/g, " ")
|
|
34
|
+
return text.charAt(0).toUpperCase() + text.slice(1)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function newNode(segment: string, stem: string): TreeNode {
|
|
38
|
+
return { segment, stem, pages: [], dirs: new Map(), rows: [] }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function rankOf(segment: string, data: Row | undefined): number | undefined {
|
|
42
|
+
if (typeof data?.order === "number") return data.order
|
|
43
|
+
const prefix = PREFIX.exec(segment)
|
|
44
|
+
return prefix ? Number(prefix[1]) : undefined
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function compareRank(
|
|
48
|
+
a: { segment: string; rank: number | undefined },
|
|
49
|
+
b: { segment: string; rank: number | undefined },
|
|
50
|
+
): number {
|
|
51
|
+
if (a.rank !== undefined && b.rank === undefined) return -1
|
|
52
|
+
if (a.rank === undefined && b.rank !== undefined) return 1
|
|
53
|
+
if (a.rank !== undefined && a.rank !== b.rank!) return a.rank - b.rank!
|
|
54
|
+
return a.segment < b.segment ? -1 : a.segment > b.segment ? 1 : 0
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function extras(target: NavigationItem, source: Row | undefined, fields: readonly string[]): void {
|
|
58
|
+
if (!source) return
|
|
59
|
+
for (const field of fields) {
|
|
60
|
+
const head = field.split(".")[0]!
|
|
61
|
+
if (!BASE_KEYS.has(head) && source[head] !== null && source[head] !== undefined)
|
|
62
|
+
target[head] = structuredClone(source[head])
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const navOf = (row: Row | undefined): Row => (isRecord(row?.navigation) ? (row!.navigation as Row) : {})
|
|
67
|
+
const text = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value : undefined)
|
|
68
|
+
|
|
69
|
+
function pathOfDir(node: TreeNode, depth: number): string {
|
|
70
|
+
const row = node.rows[0]!
|
|
71
|
+
const stemSegments = String(row.stem).split("/")
|
|
72
|
+
const own = strip(stemSegments.at(-1)!) === "index" ? stemSegments.length - 1 : stemSegments.length
|
|
73
|
+
const segments = String(row.path).split("/").filter(Boolean)
|
|
74
|
+
const prefix = segments.length - own
|
|
75
|
+
return prefix >= 0 && segments.length >= prefix + depth
|
|
76
|
+
? `/${segments.slice(0, prefix + depth).join("/")}`
|
|
77
|
+
: `/${node.stem.split("/").map(strip).join("/")}`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function leaf(row: Row, segment: string, fields: readonly string[]): NavigationItem {
|
|
81
|
+
const nav = navOf(row)
|
|
82
|
+
const item: NavigationItem = { title: "", path: "", stem: "" }
|
|
83
|
+
extras(item, row, fields)
|
|
84
|
+
item.title = text(nav.title) ?? text(row.title) ?? humanize(segment)
|
|
85
|
+
item.path = String(row.path)
|
|
86
|
+
item.stem = String(row.stem)
|
|
87
|
+
const icon = text(nav.icon)
|
|
88
|
+
if (icon !== undefined) item.icon = icon
|
|
89
|
+
return item
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function itemsOf(node: TreeNode, depth: number, fields: readonly string[]): NavigationItem[] {
|
|
93
|
+
const entries: Array<{ segment: string; rank: number | undefined; item: NavigationItem }> = []
|
|
94
|
+
for (const { segment, row } of node.pages) {
|
|
95
|
+
if (row.navigation !== false)
|
|
96
|
+
entries.push({ segment, rank: rankOf(segment, undefined), item: leaf(row, segment, fields) })
|
|
97
|
+
}
|
|
98
|
+
for (const dir of node.dirs.values()) {
|
|
99
|
+
if (dir.index?.navigation === false) continue
|
|
100
|
+
const children = itemsOf(dir, depth + 1, fields)
|
|
101
|
+
if (!dir.index && !children.length) continue
|
|
102
|
+
const nav = navOf(dir.index)
|
|
103
|
+
const item: NavigationItem = { title: "", path: "", stem: "" }
|
|
104
|
+
extras(item, dir.index, fields)
|
|
105
|
+
extras(item, dir.data, fields)
|
|
106
|
+
item.title = text(dir.data?.title) ?? text(nav.title) ?? text(dir.index?.title) ?? humanize(dir.segment)
|
|
107
|
+
item.path = dir.index ? String(dir.index.path) : pathOfDir(dir, depth + 1)
|
|
108
|
+
item.stem = dir.stem
|
|
109
|
+
const icon = text(dir.data?.icon) ?? text(nav.icon)
|
|
110
|
+
if (icon !== undefined) item.icon = icon
|
|
111
|
+
if (children.length) item.children = children
|
|
112
|
+
entries.push({ segment: dir.segment, rank: rankOf(dir.segment, dir.data), item })
|
|
113
|
+
}
|
|
114
|
+
return entries.toSorted(compareRank).map(({ item }) => item)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The tree of a page collection's rows `{ stem, path, title, navigation, navigationDirs, ...extra }`. */
|
|
118
|
+
export function buildNavigation(rows: readonly Row[], fields: readonly string[] = []): NavigationItem[] {
|
|
119
|
+
const root = newNode("", "")
|
|
120
|
+
for (const row of rows) {
|
|
121
|
+
const segments = String(row.stem).split("/")
|
|
122
|
+
let node = root
|
|
123
|
+
segments.slice(0, -1).forEach((segment, index) => {
|
|
124
|
+
let next = node.dirs.get(segment)
|
|
125
|
+
if (!next) node.dirs.set(segment, (next = newNode(segment, segments.slice(0, index + 1).join("/"))))
|
|
126
|
+
next.rows.push(row)
|
|
127
|
+
const data = isRecord(row.navigationDirs) ? row.navigationDirs[next.stem] : undefined
|
|
128
|
+
if (isRecord(data)) next.data = { ...next.data, ...data }
|
|
129
|
+
node = next
|
|
130
|
+
})
|
|
131
|
+
const last = segments.at(-1)!
|
|
132
|
+
if (strip(last) === "index") node.index = row
|
|
133
|
+
else node.pages.push({ segment: last, row })
|
|
134
|
+
}
|
|
135
|
+
const items = itemsOf(root, 0, fields)
|
|
136
|
+
if (root.index && root.index.navigation !== false) items.unshift(leaf(root.index, "index", fields))
|
|
137
|
+
return items
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** What `queryCollectionNavigation` runs: one `select` query, then the tree. */
|
|
141
|
+
export async function navigationOf(
|
|
142
|
+
query: () => CollectionQueryBuilder,
|
|
143
|
+
extraFields: readonly string[] = [],
|
|
144
|
+
): Promise<NavigationItem[]> {
|
|
145
|
+
if (!Array.isArray(extraFields) || !extraFields.every((field) => typeof field === "string"))
|
|
146
|
+
throw new QueryError("queryCollectionNavigation: extraFields must be an array of field names")
|
|
147
|
+
const rows = await query()
|
|
148
|
+
.select("stem", "path", "title", "navigation", "navigationDirs", ...extraFields)
|
|
149
|
+
.all()
|
|
150
|
+
return buildNavigation(rows as Row[], extraFields)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface SurroundingsOptions<F extends string = never> {
|
|
154
|
+
/** How many entries before the path; default 1. */
|
|
155
|
+
before?: number
|
|
156
|
+
/** How many entries after the path; default 1. */
|
|
157
|
+
after?: number
|
|
158
|
+
/** Fields returned next to `id` and `path`. */
|
|
159
|
+
fields?: F[]
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const count = (value: unknown, name: string): number => {
|
|
163
|
+
if (value === undefined) return 1
|
|
164
|
+
if (!Number.isSafeInteger(value) || (value as number) < 0)
|
|
165
|
+
throw new QueryError(`queryCollectionItemSurroundings: ${name} must be a non-negative integer`)
|
|
166
|
+
return value as number
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** `[...previous, ...next]` around `path` in the collection's order, `null` where there is none. */
|
|
170
|
+
export async function surroundingsOf<T = ContentEntry, F extends string = never>(
|
|
171
|
+
query: () => CollectionQueryBuilder<T>,
|
|
172
|
+
path: string,
|
|
173
|
+
options: SurroundingsOptions<F> = {},
|
|
174
|
+
): Promise<Array<QueryResult<T, "path" | F> | null>> {
|
|
175
|
+
const before = count(options.before, "before")
|
|
176
|
+
const after = count(options.after, "after")
|
|
177
|
+
const fields: string[] = options.fields ?? []
|
|
178
|
+
if (!Array.isArray(fields))
|
|
179
|
+
throw new QueryError("queryCollectionItemSurroundings: fields must be an array of field names")
|
|
180
|
+
const rows = (await query()
|
|
181
|
+
.select("path", ...fields)
|
|
182
|
+
.all()) as unknown as Array<QueryResult<T, "path" | F>>
|
|
183
|
+
const at = rows.findIndex((row) => (row as unknown as Row).path === path)
|
|
184
|
+
const around = (from: number, to: number): Array<QueryResult<T, "path" | F> | null> =>
|
|
185
|
+
Array.from({ length: to - from }, (_, index) => (at < 0 ? null : (rows[at + from + index] ?? null)))
|
|
186
|
+
return [...around(-before, 0), ...around(1, after + 1)]
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function walk(
|
|
190
|
+
items: readonly NavigationItem[],
|
|
191
|
+
path: string,
|
|
192
|
+
trail: NavigationItem[] = [],
|
|
193
|
+
): NavigationItem[] | undefined {
|
|
194
|
+
for (const item of items) {
|
|
195
|
+
if (item.path === path) return [...trail, item]
|
|
196
|
+
const found = item.children && walk(item.children, path, [...trail, item])
|
|
197
|
+
if (found) return found
|
|
198
|
+
}
|
|
199
|
+
return undefined
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const bare = ({ children: _, ...item }: NavigationItem): NavigationItem => item
|
|
203
|
+
|
|
204
|
+
/** The title of the parent of the item at `path`; `undefined` at the top level or for an unknown path. */
|
|
205
|
+
export function findPageHeadline(tree: readonly NavigationItem[], path: string): string | undefined {
|
|
206
|
+
return walk(tree, path)?.at(-2)?.title
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The items from the top level down to the one at `path`, each without its `children`; empty for an unknown path. */
|
|
210
|
+
export function findPageBreadcrumb(tree: readonly NavigationItem[], path: string): NavigationItem[] {
|
|
211
|
+
return (walk(tree, path) ?? []).map(bare)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The children of the item at `path`; empty for a leaf or an unknown path. */
|
|
215
|
+
export function findPageChildren(tree: readonly NavigationItem[], path: string): NavigationItem[] {
|
|
216
|
+
return walk(tree, path)?.at(-1)?.children ?? []
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The items beside the one at `path`, itself left out; empty for an unknown path. */
|
|
220
|
+
export function findPageSiblings(tree: readonly NavigationItem[], path: string): NavigationItem[] {
|
|
221
|
+
const trail = walk(tree, path)
|
|
222
|
+
if (!trail) return []
|
|
223
|
+
const parent = trail.at(-2)
|
|
224
|
+
return (parent ? parent.children! : tree).filter((item) => item.path !== path)
|
|
225
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/// <reference path="../env.d.ts" />
|
|
2
|
+
import client from "#hamur/content/client"
|
|
3
|
+
import { definePlugin } from "hamur/app"
|
|
4
|
+
import { queryCollection } from "../query.ts"
|
|
5
|
+
import { setPageSource } from "./page-source.ts"
|
|
6
|
+
|
|
7
|
+
export default definePlugin(() =>
|
|
8
|
+
setPageSource({
|
|
9
|
+
query: (name) => queryCollection(name as never) as never,
|
|
10
|
+
types: Object.fromEntries(Object.entries(client.collections).map(([name, { type }]) => [name, type])),
|
|
11
|
+
...(client.raw === undefined ? {} : { rawBase: client.raw }),
|
|
12
|
+
}),
|
|
13
|
+
)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { CollectionQueryBuilder } from "./query.ts"
|
|
2
|
+
import type { PageEntry } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
export interface PageSource {
|
|
5
|
+
/** `queryCollection`, handed over so the adapters import no `#hamur/content/*` module an app without the content module lacks. */
|
|
6
|
+
query(name: string): CollectionQueryBuilder<PageEntry>
|
|
7
|
+
/** The type of each collection of `content.config.ts`. */
|
|
8
|
+
types: Record<string, "page" | "data">
|
|
9
|
+
/** `app.baseURL` when `content.raw` is on: the pages then have a Markdown copy at `<path>.md`. */
|
|
10
|
+
rawBase?: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
let current: PageSource | undefined
|
|
14
|
+
|
|
15
|
+
export function setPageSource(source: PageSource): void {
|
|
16
|
+
current = source
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function pageSource(): PageSource {
|
|
20
|
+
if (!current) throw new Error("useContentPage: add @hamur/content to modules")
|
|
21
|
+
return current
|
|
22
|
+
}
|