@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,266 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import type { Logger } from "hamur/server"
|
|
4
|
+
import { ContentError } from "../error.ts"
|
|
5
|
+
import type { RemoteSourceOptions } from "../types.ts"
|
|
6
|
+
|
|
7
|
+
export const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024
|
|
8
|
+
export const MAX_UNPACKED_BYTES = 500 * 1024 * 1024
|
|
9
|
+
|
|
10
|
+
export interface Repository {
|
|
11
|
+
host: "github" | "gitlab"
|
|
12
|
+
/** `org/docs`, or `group/sub/docs` on GitLab. */
|
|
13
|
+
path: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface FetchRepositoryOptions {
|
|
17
|
+
cacheDir: string
|
|
18
|
+
logger?: Logger
|
|
19
|
+
maxBytes?: number
|
|
20
|
+
maxUnpackedBytes?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const HOSTS: Record<string, Repository["host"]> = { "github.com": "github", "gitlab.com": "gitlab" }
|
|
24
|
+
|
|
25
|
+
/** The URL as errors show it: without a user or password, so a token written into it is not echoed. */
|
|
26
|
+
function shownOf(repository: string): string {
|
|
27
|
+
try {
|
|
28
|
+
const url = new URL(repository)
|
|
29
|
+
if (!url.username && !url.password) return repository
|
|
30
|
+
url.username = ""
|
|
31
|
+
url.password = ""
|
|
32
|
+
return url.href
|
|
33
|
+
} catch {
|
|
34
|
+
return repository
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** An `https:` URL of a github.com or gitlab.com repository. */
|
|
39
|
+
export function parseRepository(repository: string): Repository {
|
|
40
|
+
let url: URL | undefined
|
|
41
|
+
try {
|
|
42
|
+
url = new URL(repository)
|
|
43
|
+
} catch {}
|
|
44
|
+
const host = url ? HOSTS[url.hostname] : undefined
|
|
45
|
+
const path = (url?.pathname ?? "")
|
|
46
|
+
.replace(/\/+$/, "")
|
|
47
|
+
.replace(/\.git$/, "")
|
|
48
|
+
.slice(1)
|
|
49
|
+
const segments = path.split("/")
|
|
50
|
+
const plain =
|
|
51
|
+
url !== undefined &&
|
|
52
|
+
url.protocol === "https:" &&
|
|
53
|
+
!url.username &&
|
|
54
|
+
!url.password &&
|
|
55
|
+
!url.port &&
|
|
56
|
+
!url.search &&
|
|
57
|
+
!url.hash
|
|
58
|
+
const shaped =
|
|
59
|
+
segments.every((segment) => segment !== "" && segment !== "." && segment !== "..") &&
|
|
60
|
+
(host === "github" ? segments.length === 2 : segments.length >= 2)
|
|
61
|
+
if (!plain || host === undefined || !shaped)
|
|
62
|
+
throw new ContentError("HAMUR_E5361", `content: ${shownOf(repository)} is not a GitHub or GitLab repository URL`)
|
|
63
|
+
return { host, path }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const refPath = (ref: string): string => ref.split("/").map(encodeURIComponent).join("/")
|
|
67
|
+
|
|
68
|
+
/** The tarball URL and its headers; the token only ever goes in a header. */
|
|
69
|
+
export function archiveRequest(
|
|
70
|
+
repository: Repository,
|
|
71
|
+
ref: { kind: "branch" | "tag"; name: string } | undefined,
|
|
72
|
+
token: string | undefined,
|
|
73
|
+
): { url: string; headers: Record<string, string> } {
|
|
74
|
+
if (repository.host === "gitlab") {
|
|
75
|
+
const sha = ref ? `?sha=${encodeURIComponent(ref.name)}` : ""
|
|
76
|
+
return {
|
|
77
|
+
url: `https://gitlab.com/api/v4/projects/${encodeURIComponent(repository.path)}/repository/archive.tar.gz${sha}`,
|
|
78
|
+
headers: token ? { "private-token": token } : {},
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (token)
|
|
82
|
+
return {
|
|
83
|
+
url: `https://api.github.com/repos/${repository.path}/tarball${ref ? `/${refPath(ref.name)}` : ""}`,
|
|
84
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" },
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
url: `https://codeload.github.com/${repository.path}/tar.gz/${ref ? `refs/${ref.kind === "branch" ? "heads" : "tags"}/${refPath(ref.name)}` : "HEAD"}`,
|
|
88
|
+
headers: {},
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const unsafe = (name: string): boolean =>
|
|
93
|
+
name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name) || name.split(/[\\/]/).includes("..")
|
|
94
|
+
|
|
95
|
+
/** The stream's bytes, or `undefined` once more than `max` have arrived. */
|
|
96
|
+
async function readCapped(
|
|
97
|
+
stream: ReadableStream<Uint8Array> | null,
|
|
98
|
+
max: number,
|
|
99
|
+
): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
100
|
+
const chunks: Uint8Array[] = []
|
|
101
|
+
let size = 0
|
|
102
|
+
if (stream) {
|
|
103
|
+
const reader = stream.getReader()
|
|
104
|
+
for (;;) {
|
|
105
|
+
const { done, value } = await reader.read()
|
|
106
|
+
if (done) break
|
|
107
|
+
size += value.byteLength
|
|
108
|
+
if (size > max) {
|
|
109
|
+
await reader.cancel()
|
|
110
|
+
return undefined
|
|
111
|
+
}
|
|
112
|
+
chunks.push(value)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const bytes = new Uint8Array(size)
|
|
116
|
+
let offset = 0
|
|
117
|
+
for (const chunk of chunks) {
|
|
118
|
+
bytes.set(chunk, offset)
|
|
119
|
+
offset += chunk.byteLength
|
|
120
|
+
}
|
|
121
|
+
return bytes
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const random = (): string => crypto.randomUUID()
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Unpacks the archive into a version directory named by its SHA-256, below `base`, without the top folder GitHub and
|
|
128
|
+
* GitLab put every file in, then points `base/current` at it. A version directory is never replaced, so a build reading
|
|
129
|
+
* a copy keeps it while another process fetches.
|
|
130
|
+
*/
|
|
131
|
+
async function unpack(
|
|
132
|
+
bytes: Uint8Array<ArrayBuffer>,
|
|
133
|
+
base: string,
|
|
134
|
+
shown: string,
|
|
135
|
+
maxUnpacked: number,
|
|
136
|
+
): Promise<string> {
|
|
137
|
+
let files: Map<string, File>
|
|
138
|
+
let version: string
|
|
139
|
+
try {
|
|
140
|
+
const gzip = bytes[0] === 0x1f && bytes[1] === 0x8b
|
|
141
|
+
const tar = gzip
|
|
142
|
+
? await readCapped(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")), maxUnpacked)
|
|
143
|
+
: bytes.byteLength > maxUnpacked
|
|
144
|
+
? undefined
|
|
145
|
+
: bytes
|
|
146
|
+
if (!tar)
|
|
147
|
+
throw new ContentError(
|
|
148
|
+
"HAMUR_E5362",
|
|
149
|
+
`content: cannot read the archive of ${shown} (larger than ${maxUnpacked} bytes unpacked)`,
|
|
150
|
+
)
|
|
151
|
+
files = await new Bun.Archive(tar).files()
|
|
152
|
+
version = new Bun.CryptoHasher("sha256").update(tar).digest("hex")
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error instanceof ContentError) throw error
|
|
155
|
+
throw new ContentError(
|
|
156
|
+
"HAMUR_E5363",
|
|
157
|
+
`content: cannot read the archive of ${shown} (${error instanceof Error ? error.message : String(error)})`,
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
let total = 0
|
|
161
|
+
for (const [name, file] of files) {
|
|
162
|
+
if (unsafe(name))
|
|
163
|
+
throw new ContentError("HAMUR_E5364", `content: ${shown}: archive entry "${name}" leaves the repository`)
|
|
164
|
+
total += file.size
|
|
165
|
+
}
|
|
166
|
+
if (total > maxUnpacked)
|
|
167
|
+
throw new ContentError(
|
|
168
|
+
"HAMUR_E5362",
|
|
169
|
+
`content: cannot read the archive of ${shown} (larger than ${maxUnpacked} bytes unpacked)`,
|
|
170
|
+
)
|
|
171
|
+
const dir = join(base, version)
|
|
172
|
+
if (!(await isDirectory(dir))) {
|
|
173
|
+
const temp = join(base, `${version}.${random()}.tmp`)
|
|
174
|
+
try {
|
|
175
|
+
await mkdir(temp, { recursive: true })
|
|
176
|
+
for (const [name, file] of files) {
|
|
177
|
+
const slash = name.indexOf("/")
|
|
178
|
+
if (slash < 0 || slash === name.length - 1) continue
|
|
179
|
+
await Bun.write(join(temp, name.slice(slash + 1)), file)
|
|
180
|
+
}
|
|
181
|
+
await rename(temp, dir).catch((error: { code?: string }) => {
|
|
182
|
+
if (error.code !== "ENOTEMPTY" && error.code !== "EEXIST") throw error
|
|
183
|
+
})
|
|
184
|
+
} finally {
|
|
185
|
+
await rm(temp, { recursive: true, force: true })
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const previous = await currentVersion(base)
|
|
189
|
+
const pointer = join(base, `current.${random()}.tmp`)
|
|
190
|
+
await Bun.write(pointer, version)
|
|
191
|
+
await rename(pointer, join(base, "current"))
|
|
192
|
+
for (const name of await readdir(base)) {
|
|
193
|
+
if (/^[0-9a-f]{64}$/.test(name) && name !== version && name !== previous)
|
|
194
|
+
await rm(join(base, name), { recursive: true, force: true })
|
|
195
|
+
}
|
|
196
|
+
return dir
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const isDirectory = (path: string): Promise<boolean> =>
|
|
200
|
+
stat(path).then(
|
|
201
|
+
(info) => info.isDirectory(),
|
|
202
|
+
() => false,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
async function currentVersion(base: string): Promise<string | undefined> {
|
|
206
|
+
try {
|
|
207
|
+
const version = (await readFile(join(base, "current"), "utf8")).trim()
|
|
208
|
+
return /^[0-9a-f]{64}$/.test(version) ? version : undefined
|
|
209
|
+
} catch {
|
|
210
|
+
return undefined
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Downloads the repository's tarball below `<cacheDir>/content/<sha256 of repository + ref>` and returns the unpacked copy; a failed fetch falls back to the last copy. */
|
|
215
|
+
export async function fetchRepository(
|
|
216
|
+
source: RemoteSourceOptions,
|
|
217
|
+
{ cacheDir, logger, maxBytes = MAX_ARCHIVE_BYTES, maxUnpackedBytes = MAX_UNPACKED_BYTES }: FetchRepositoryOptions,
|
|
218
|
+
): Promise<string> {
|
|
219
|
+
const shown = shownOf(source.repository)
|
|
220
|
+
const repository = parseRepository(source.repository)
|
|
221
|
+
if (source.branch !== undefined && source.tag !== undefined)
|
|
222
|
+
throw new ContentError("HAMUR_E5365", `content: ${shown}: set branch or tag, not both`)
|
|
223
|
+
const ref =
|
|
224
|
+
source.branch !== undefined
|
|
225
|
+
? { kind: "branch" as const, name: source.branch }
|
|
226
|
+
: source.tag !== undefined
|
|
227
|
+
? { kind: "tag" as const, name: source.tag }
|
|
228
|
+
: undefined
|
|
229
|
+
const token = source.auth?.token || undefined
|
|
230
|
+
const key = new Bun.CryptoHasher("sha256")
|
|
231
|
+
.update(JSON.stringify([source.repository, ref?.kind ?? null, ref?.name ?? null]))
|
|
232
|
+
.digest("hex")
|
|
233
|
+
const base = join(cacheDir, "content", key)
|
|
234
|
+
const redact = (text: string): string => (token ? text.split(token).join("***") : text)
|
|
235
|
+
const fallback = async (reason: string): Promise<string> => {
|
|
236
|
+
const version = await currentVersion(base)
|
|
237
|
+
if (version === undefined || !(await isDirectory(join(base, version)))) {
|
|
238
|
+
throw new ContentError(
|
|
239
|
+
"HAMUR_E5366",
|
|
240
|
+
`content: cannot fetch ${shown} and no cached copy exists (${redact(reason)})`,
|
|
241
|
+
)
|
|
242
|
+
}
|
|
243
|
+
logger?.warn(`using the cached copy of ${shown}`)
|
|
244
|
+
return join(base, version)
|
|
245
|
+
}
|
|
246
|
+
const { url, headers } = archiveRequest(repository, ref, token)
|
|
247
|
+
let bytes: Uint8Array<ArrayBuffer> | undefined
|
|
248
|
+
try {
|
|
249
|
+
const response = await globalThis.fetch(url, { headers })
|
|
250
|
+
if (response.status >= 500 || response.status === 429) return await fallback(String(response.status))
|
|
251
|
+
if (!response.ok) throw new ContentError("HAMUR_E5367", `content: cannot fetch ${shown} (${response.status})`)
|
|
252
|
+
bytes =
|
|
253
|
+
Number(response.headers.get("content-length") ?? 0) > maxBytes
|
|
254
|
+
? undefined
|
|
255
|
+
: await readCapped(response.body, maxBytes)
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (error instanceof ContentError) throw error
|
|
258
|
+
return fallback(error instanceof Error ? error.message : String(error))
|
|
259
|
+
}
|
|
260
|
+
if (!bytes)
|
|
261
|
+
throw new ContentError(
|
|
262
|
+
"HAMUR_E5362",
|
|
263
|
+
`content: cannot fetch ${shown} (the archive is larger than ${maxBytes} bytes)`,
|
|
264
|
+
)
|
|
265
|
+
return unpack(bytes, base, shown, maxUnpackedBytes)
|
|
266
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { join, relative, sep } from "node:path"
|
|
2
|
+
import { ContentError } from "../error.ts"
|
|
3
|
+
import { DATA_FORMATS, parseDataText } from "./data.ts"
|
|
4
|
+
import { setupSources } from "../source.ts"
|
|
5
|
+
import type { CollectionSource, ContentLoader, LoaderContext } from "../types.ts"
|
|
6
|
+
|
|
7
|
+
const FORMATS = new Set<string>(["md", ...DATA_FORMATS])
|
|
8
|
+
|
|
9
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
10
|
+
value !== null && typeof value === "object" && !Array.isArray(value)
|
|
11
|
+
|
|
12
|
+
const DIRECTORY_FILES = [".navigation.yml", ".navigation.yaml"]
|
|
13
|
+
|
|
14
|
+
/** The `.navigation.yml` of each directory above `relativePath`, by directory stem; each file is read once. */
|
|
15
|
+
async function directoryData(
|
|
16
|
+
cwd: string,
|
|
17
|
+
relativePath: string,
|
|
18
|
+
cache: Map<string, Promise<Record<string, unknown> | undefined>>,
|
|
19
|
+
rootDir: string,
|
|
20
|
+
): Promise<Record<string, Record<string, unknown>> | undefined> {
|
|
21
|
+
const segments = relativePath.split("/").slice(0, -1)
|
|
22
|
+
const found: Record<string, Record<string, unknown>> = {}
|
|
23
|
+
for (let depth = 1; depth <= segments.length; depth++) {
|
|
24
|
+
const dir = segments.slice(0, depth).join("/")
|
|
25
|
+
const key = join(cwd, dir)
|
|
26
|
+
let read = cache.get(key)
|
|
27
|
+
if (!read) {
|
|
28
|
+
read = (async () => {
|
|
29
|
+
for (const name of DIRECTORY_FILES) {
|
|
30
|
+
const file = Bun.file(join(key, name))
|
|
31
|
+
if (!(await file.exists())) continue
|
|
32
|
+
const shown = relative(rootDir, join(key, name)).split(sep).join("/")
|
|
33
|
+
const value = parseDataText(await file.text(), "yml", shown)
|
|
34
|
+
if (!isObject(value)) throw new ContentError("HAMUR_E5357", `${shown}: a ${name} file holds an object`)
|
|
35
|
+
return value
|
|
36
|
+
}
|
|
37
|
+
return undefined
|
|
38
|
+
})()
|
|
39
|
+
cache.set(key, read)
|
|
40
|
+
}
|
|
41
|
+
const data = await read
|
|
42
|
+
if (data) found[dir] = data
|
|
43
|
+
}
|
|
44
|
+
return Object.keys(found).length ? found : undefined
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Reads a file of a transformer's extension through its `parse`. */
|
|
48
|
+
async function parseWith(
|
|
49
|
+
ctx: LoaderContext,
|
|
50
|
+
extension: string,
|
|
51
|
+
id: string,
|
|
52
|
+
shown: string,
|
|
53
|
+
body: string,
|
|
54
|
+
): Promise<Record<string, unknown> | undefined> {
|
|
55
|
+
const transformer = ctx.transformers.find(
|
|
56
|
+
(item) => item.parse !== undefined && item.extensions.includes(`.${extension}`),
|
|
57
|
+
)
|
|
58
|
+
if (!transformer) return undefined
|
|
59
|
+
let value: unknown
|
|
60
|
+
try {
|
|
61
|
+
value = await transformer.parse!({ id, path: shown, extension, body })
|
|
62
|
+
} catch (error) {
|
|
63
|
+
throw new ContentError(
|
|
64
|
+
"HAMUR_E5347",
|
|
65
|
+
`${shown}: transformer "${transformer.name}" failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
if (!isObject(value))
|
|
69
|
+
throw new ContentError(
|
|
70
|
+
"HAMUR_E5348",
|
|
71
|
+
`${shown}: transformer "${transformer.name}" must return an object from parse`,
|
|
72
|
+
)
|
|
73
|
+
return value
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** What a `source` desugars to; sources of one collection share a file list, so a file matched twice is read once. */
|
|
77
|
+
export function sourceLoader(source: CollectionSource, cacheDir?: string): ContentLoader {
|
|
78
|
+
return {
|
|
79
|
+
name: "glob",
|
|
80
|
+
async load(ctx) {
|
|
81
|
+
const directories = new Map<string, Promise<Record<string, unknown> | undefined>>()
|
|
82
|
+
for (const file of await setupSources(ctx.rootDir, source, {
|
|
83
|
+
...(cacheDir === undefined ? {} : { cacheDir }),
|
|
84
|
+
logger: ctx.logger,
|
|
85
|
+
})) {
|
|
86
|
+
const shown = relative(ctx.rootDir, file.file).split(sep).join("/")
|
|
87
|
+
const transformed =
|
|
88
|
+
!FORMATS.has(file.extension) &&
|
|
89
|
+
ctx.transformers.some((item) => item.parse !== undefined && item.extensions.includes(`.${file.extension}`))
|
|
90
|
+
if (!FORMATS.has(file.extension) && !transformed)
|
|
91
|
+
throw new ContentError(
|
|
92
|
+
"HAMUR_E5355",
|
|
93
|
+
`${shown}: .${file.extension} is not a content format (md, yml, yaml, json, json5, toml, csv)`,
|
|
94
|
+
)
|
|
95
|
+
const text = await ctx.beforeParse({
|
|
96
|
+
id: file.stem,
|
|
97
|
+
path: shown,
|
|
98
|
+
extension: file.extension,
|
|
99
|
+
body: await Bun.file(file.file).text(),
|
|
100
|
+
})
|
|
101
|
+
const navigationDirs =
|
|
102
|
+
ctx.type === "page" ? await directoryData(file.cwd, file.relative, directories, ctx.rootDir) : undefined
|
|
103
|
+
const entry = {
|
|
104
|
+
stem: file.stem,
|
|
105
|
+
path: file.path,
|
|
106
|
+
file: file.file,
|
|
107
|
+
...(navigationDirs ? { navigationDirs } : {}),
|
|
108
|
+
}
|
|
109
|
+
const dirs = navigationDirs ? `\0${JSON.stringify(navigationDirs)}` : ""
|
|
110
|
+
if (file.extension === "md") {
|
|
111
|
+
ctx.store.set({
|
|
112
|
+
...entry,
|
|
113
|
+
id: file.stem,
|
|
114
|
+
data: {},
|
|
115
|
+
body: text,
|
|
116
|
+
digest: ctx.digest(`${shown}\0${text}${dirs}`),
|
|
117
|
+
})
|
|
118
|
+
continue
|
|
119
|
+
}
|
|
120
|
+
const value = transformed
|
|
121
|
+
? (await parseWith(ctx, file.extension, file.stem, shown, text))!
|
|
122
|
+
: parseDataText(text, file.extension, shown, ctx.csv)
|
|
123
|
+
const options = file.extension === "csv" ? `\0${ctx.csv.delimiter}${ctx.csv.header}` : ""
|
|
124
|
+
if (ctx.type === "page") {
|
|
125
|
+
if (Array.isArray(value))
|
|
126
|
+
throw new ContentError(
|
|
127
|
+
"HAMUR_E5356",
|
|
128
|
+
`${shown}: a page collection entry is one document; move the file to a data collection`,
|
|
129
|
+
)
|
|
130
|
+
if (!isObject(value)) throw new ContentError("HAMUR_E5357", `${shown}: a page file holds an object`)
|
|
131
|
+
const { body, ...data } = value
|
|
132
|
+
const markdown = transformed && typeof body === "string"
|
|
133
|
+
ctx.store.set({
|
|
134
|
+
...entry,
|
|
135
|
+
id: file.stem,
|
|
136
|
+
data: markdown ? data : value,
|
|
137
|
+
...(markdown ? { body } : {}),
|
|
138
|
+
digest: ctx.digest(`${shown}\0${text}${dirs}${options}`),
|
|
139
|
+
})
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
for (const [index, item] of (Array.isArray(value) ? value : [value]).entries()) {
|
|
143
|
+
const label = Array.isArray(value) ? String(index) : undefined
|
|
144
|
+
if (!isObject(item))
|
|
145
|
+
throw new ContentError(
|
|
146
|
+
"HAMUR_E5350",
|
|
147
|
+
`${shown}: ${label === undefined ? "" : `${label}: `}a data entry is an object`,
|
|
148
|
+
)
|
|
149
|
+
ctx.store.set({
|
|
150
|
+
...entry,
|
|
151
|
+
id: label === undefined ? file.stem : `${file.stem}/${label}`,
|
|
152
|
+
data: item,
|
|
153
|
+
digest: ctx.digest(`${shown}\0${label ?? ""}\0${text}${options}`),
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface GlobOptions {
|
|
162
|
+
/** A glob relative to `base`. */
|
|
163
|
+
pattern: string
|
|
164
|
+
/** A directory relative to `<rootDir>/content`; default that directory. */
|
|
165
|
+
base?: string
|
|
166
|
+
exclude?: string[]
|
|
167
|
+
/** The path prefix of a page collection; default `/`. */
|
|
168
|
+
prefix?: string
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Reads `.md`, `.yml`, `.yaml`, `.json`, `.json5`, `.toml` and `.csv` files matching `pattern` below `base`. */
|
|
172
|
+
export function glob({ pattern, base, exclude, prefix }: GlobOptions): ContentLoader {
|
|
173
|
+
return sourceLoader({
|
|
174
|
+
include: pattern,
|
|
175
|
+
...(base === undefined ? {} : { cwd: base }),
|
|
176
|
+
...(exclude === undefined ? {} : { exclude }),
|
|
177
|
+
...(prefix === undefined ? {} : { prefix }),
|
|
178
|
+
})
|
|
179
|
+
}
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { defineModule } from "hamur/kit"
|
|
2
|
+
import { setupDev } from "./build/dev.ts"
|
|
3
|
+
import { setupIndex } from "./build/index.ts"
|
|
4
|
+
import { setupLive } from "./build/live.ts"
|
|
5
|
+
import { setupPrerender } from "./build/prerender.ts"
|
|
6
|
+
import { setupQuery } from "./build/query.ts"
|
|
7
|
+
import { setupRaw } from "./build/raw.ts"
|
|
8
|
+
import { setupSearch } from "./build/search.ts"
|
|
9
|
+
import { setupTypes } from "./build/types.ts"
|
|
10
|
+
import { setupConfig } from "./config.ts"
|
|
11
|
+
import type { ContentOptions } from "./types.ts"
|
|
12
|
+
|
|
13
|
+
export default defineModule<ContentOptions>({
|
|
14
|
+
meta: { name: "content", configKey: "content", hooks: ["content:file:beforeParse", "content:file:afterParse"] },
|
|
15
|
+
async setup(options, hamur) {
|
|
16
|
+
const config = await setupConfig(hamur.options.rootDir)
|
|
17
|
+
const index = setupIndex(hamur, config, options)
|
|
18
|
+
setupQuery(options, config, hamur)
|
|
19
|
+
setupPrerender(options, config, index.read, hamur)
|
|
20
|
+
setupRaw(options, config, index, hamur)
|
|
21
|
+
const search = setupSearch(options, config, index.read, hamur.options.dev)
|
|
22
|
+
setupDev(hamur, config, index, search)
|
|
23
|
+
setupLive(config, hamur)
|
|
24
|
+
setupTypes(config, hamur)
|
|
25
|
+
},
|
|
26
|
+
})
|
package/src/query.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/// <reference path="./env.d.ts" />
|
|
2
|
+
import client from "#hamur/content/client"
|
|
3
|
+
import { noteDependency } from "hamur/app"
|
|
4
|
+
import { createClientQuery } from "./runtime/client.ts"
|
|
5
|
+
import {
|
|
6
|
+
findPageBreadcrumb,
|
|
7
|
+
findPageChildren,
|
|
8
|
+
findPageHeadline,
|
|
9
|
+
findPageSiblings,
|
|
10
|
+
navigationOf,
|
|
11
|
+
surroundingsOf,
|
|
12
|
+
type NavigationItem,
|
|
13
|
+
type SurroundingsOptions,
|
|
14
|
+
} from "./runtime/navigation.ts"
|
|
15
|
+
import { createQuery, QueryError, queryStore, type CollectionQueryBuilder } from "./runtime/query.ts"
|
|
16
|
+
import {
|
|
17
|
+
searchSectionsOf,
|
|
18
|
+
type HeadingTag,
|
|
19
|
+
type SearchSection,
|
|
20
|
+
type SearchSectionsOptions,
|
|
21
|
+
} from "./runtime/sections.ts"
|
|
22
|
+
import { serverStore } from "./runtime/server-store.ts"
|
|
23
|
+
import type { CollectionField, CollectionItem, CollectionName } from "./index.ts"
|
|
24
|
+
import type { ContentEntry } from "./types.ts"
|
|
25
|
+
|
|
26
|
+
export { findPageBreadcrumb, findPageChildren, findPageHeadline, findPageSiblings }
|
|
27
|
+
export type { HeadingTag, NavigationItem, SearchSection, SearchSectionsOptions, SurroundingsOptions }
|
|
28
|
+
export type {
|
|
29
|
+
CollectionQuery,
|
|
30
|
+
CollectionQueryBuilder,
|
|
31
|
+
FieldHead,
|
|
32
|
+
FieldPath,
|
|
33
|
+
QueryClause,
|
|
34
|
+
QueryCondition,
|
|
35
|
+
QueryDirection,
|
|
36
|
+
QueryGroup,
|
|
37
|
+
QueryGroupBuilder,
|
|
38
|
+
QueryOperator,
|
|
39
|
+
QueryResult,
|
|
40
|
+
} from "./runtime/query.ts"
|
|
41
|
+
|
|
42
|
+
const inBrowser = createClientQuery(client)
|
|
43
|
+
|
|
44
|
+
/** On the server the store in process, in the browser `content.clientQuery`'s way. */
|
|
45
|
+
export function queryCollection<N extends CollectionName>(
|
|
46
|
+
name: N,
|
|
47
|
+
): CollectionQueryBuilder<CollectionItem<N>, never, CollectionField<N>>
|
|
48
|
+
export function queryCollection<T = ContentEntry>(name: CollectionName): CollectionQueryBuilder<T>
|
|
49
|
+
export function queryCollection(name: string): CollectionQueryBuilder<any, never, any> {
|
|
50
|
+
noteDependency(`content:${name}`)
|
|
51
|
+
if (!import.meta.server) return inBrowser(name)
|
|
52
|
+
return createQuery((query) => {
|
|
53
|
+
const store = serverStore()
|
|
54
|
+
if (!store) throw new QueryError("the content store is not loaded; add @hamur/content to modules")
|
|
55
|
+
return queryStore(store, name, query)
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The tree of a page collection by directory. */
|
|
60
|
+
export function queryCollectionNavigation(name: CollectionName, extraFields?: string[]): Promise<NavigationItem[]> {
|
|
61
|
+
noteDependency(`content:${name}`)
|
|
62
|
+
return navigationOf(() => queryCollection<ContentEntry>(name), extraFields)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The entries before and after `path` in the collection's order, `null` where there is none. */
|
|
66
|
+
export function queryCollectionItemSurroundings<N extends CollectionName, F extends string = never>(
|
|
67
|
+
name: N,
|
|
68
|
+
path: string,
|
|
69
|
+
options?: SurroundingsOptions<F>,
|
|
70
|
+
) {
|
|
71
|
+
noteDependency(`content:${name}`)
|
|
72
|
+
return surroundingsOf<CollectionItem<N>, F>(() => queryCollection<CollectionItem<N>>(name), path, options)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Every page of the collection split at its headings, from the server or the browser. */
|
|
76
|
+
export function queryCollectionSearchSections(
|
|
77
|
+
name: CollectionName,
|
|
78
|
+
options?: SearchSectionsOptions,
|
|
79
|
+
): Promise<SearchSection[]> {
|
|
80
|
+
noteDependency(`content:${name}`)
|
|
81
|
+
return searchSectionsOf(() => queryCollection<Record<string, unknown>>(name), options)
|
|
82
|
+
}
|
package/src/render.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { renderMarkdownAst, type MdHeading, type MdRoot } from "hamur/markdown"
|
|
2
|
+
import type { ContentEntry, PageEntry } from "./types.ts"
|
|
3
|
+
|
|
4
|
+
export interface RenderedEntry {
|
|
5
|
+
html: string
|
|
6
|
+
headings: MdHeading[]
|
|
7
|
+
ast: MdRoot
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Plain ESM over `renderMarkdownAst`, so it runs on every preset and in the browser. */
|
|
11
|
+
export async function renderEntry(entry: ContentEntry): Promise<RenderedEntry> {
|
|
12
|
+
if (!Array.isArray(entry.body))
|
|
13
|
+
throw new TypeError(`renderEntry needs a page collection entry (got data collection "${String(entry.collection)}")`)
|
|
14
|
+
const page = entry as PageEntry
|
|
15
|
+
return { html: renderMarkdownAst(page.body), headings: page.headings, ast: page.body }
|
|
16
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { $fetch, FetchError } from "hamur/app"
|
|
2
|
+
import type { ContentEntry } from "../types.ts"
|
|
3
|
+
import {
|
|
4
|
+
createQuery,
|
|
5
|
+
QueryError,
|
|
6
|
+
runQuery,
|
|
7
|
+
type CollectionQuery,
|
|
8
|
+
type CollectionQueryBuilder,
|
|
9
|
+
type QueriedCollection,
|
|
10
|
+
} from "./query.ts"
|
|
11
|
+
|
|
12
|
+
export const QUERY_PATH = "/_hamur/content/query"
|
|
13
|
+
|
|
14
|
+
/** One collection as `#hamur/content/client` lists it; `load` only for an exposed collection under `"local"`. */
|
|
15
|
+
export interface ClientCollection extends QueriedCollection {
|
|
16
|
+
expose: boolean
|
|
17
|
+
load?: () => Promise<{ default: ContentEntry[] }>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ClientQueryConfig {
|
|
21
|
+
mode: "api" | "local"
|
|
22
|
+
/** `app.baseURL`, present when `content.raw` is on. */
|
|
23
|
+
raw?: string
|
|
24
|
+
collections: Record<string, ClientCollection>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `POST <baseURL>_hamur/content/query`; a 400 is the engine's refusal. */
|
|
28
|
+
export async function postQuery(body: { collection: string; query: CollectionQuery }): Promise<unknown> {
|
|
29
|
+
try {
|
|
30
|
+
return await $fetch<unknown>(QUERY_PATH, { method: "POST", body, retry: 0 })
|
|
31
|
+
} catch (error) {
|
|
32
|
+
const message =
|
|
33
|
+
error instanceof FetchError && error.status === 400
|
|
34
|
+
? (error.data as { message?: unknown } | undefined)?.message
|
|
35
|
+
: undefined
|
|
36
|
+
throw typeof message === "string" ? new QueryError(message) : error
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const caches = new Set<Map<string, Promise<ContentEntry[]>>>()
|
|
41
|
+
|
|
42
|
+
/** `hamur dev`: drops the fetched chunk of `name`, so the next local query fetches it again. */
|
|
43
|
+
export function forgetChunk(name: string): void {
|
|
44
|
+
for (const cache of caches) cache.delete(name)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `queryCollection` in the browser, over the endpoint or the collection's chunk fetched once. */
|
|
48
|
+
export function createClientQuery(
|
|
49
|
+
config: ClientQueryConfig,
|
|
50
|
+
post: typeof postQuery = postQuery,
|
|
51
|
+
): <T = ContentEntry>(name: string) => CollectionQueryBuilder<T> {
|
|
52
|
+
const loaded = new Map<string, Promise<ContentEntry[]>>()
|
|
53
|
+
caches.add(loaded)
|
|
54
|
+
const entries = (name: string, load: NonNullable<ClientCollection["load"]>): Promise<ContentEntry[]> => {
|
|
55
|
+
let promise = loaded.get(name)
|
|
56
|
+
if (!promise) {
|
|
57
|
+
promise = load().then((chunk) => chunk.default)
|
|
58
|
+
loaded.set(name, promise)
|
|
59
|
+
promise.catch(() => loaded.get(name) === promise && loaded.delete(name))
|
|
60
|
+
}
|
|
61
|
+
return promise
|
|
62
|
+
}
|
|
63
|
+
return <T = ContentEntry>(name: string): CollectionQueryBuilder<T> => {
|
|
64
|
+
const collection = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined
|
|
65
|
+
if (!collection) throw new QueryError(`queryCollection: unknown collection ${JSON.stringify(name)}`)
|
|
66
|
+
if (!collection.expose)
|
|
67
|
+
throw new QueryError(
|
|
68
|
+
`queryCollection(${JSON.stringify(name)}): the collection is not exposed to the client (expose: false)`,
|
|
69
|
+
)
|
|
70
|
+
const { load } = collection
|
|
71
|
+
if (config.mode === "local" && load)
|
|
72
|
+
return createQuery<T>(async (query) => runQuery(name, collection, await entries(name, load), query))
|
|
73
|
+
return createQuery<T>((query) => post({ collection: name, query }))
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { $fetch } from "hamur/app"
|
|
2
|
+
|
|
3
|
+
/** `hamur dev`: a chunk or search index fetched from the dev index, so a refetch after `content:update` gets the new entries. */
|
|
4
|
+
export function devLoad<T>(path: string): () => Promise<{ default: T }> {
|
|
5
|
+
return async () => ({ default: await $fetch<T>(path, { retry: 0 }) })
|
|
6
|
+
}
|