@hamur/content 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/chunks/{bun-render-7jxnxg3v.js → bun-render-wckjnzsa.js} +5 -3
  2. package/dist/src/index.js +132 -73
  3. package/dist/src/query.js +4 -2
  4. package/dist/src/server/index.js +1 -1
  5. package/dist/types/src/adapters/ContentRenderer.svelte +27 -0
  6. package/dist/types/src/adapters/ProseA.svelte +11 -0
  7. package/dist/types/src/adapters/ProseBlockquote.svelte +7 -0
  8. package/dist/types/src/adapters/ProseCode.svelte +7 -0
  9. package/dist/types/src/adapters/ProseEm.svelte +7 -0
  10. package/dist/types/src/adapters/ProseH1.svelte +7 -0
  11. package/dist/types/src/adapters/ProseH2.svelte +7 -0
  12. package/dist/types/src/adapters/ProseH3.svelte +7 -0
  13. package/dist/types/src/adapters/ProseH4.svelte +7 -0
  14. package/dist/types/src/adapters/ProseH5.svelte +7 -0
  15. package/dist/types/src/adapters/ProseH6.svelte +7 -0
  16. package/dist/types/src/adapters/ProseHr.svelte +5 -0
  17. package/dist/types/src/adapters/ProseImg.svelte +5 -0
  18. package/dist/types/src/adapters/ProseLi.svelte +7 -0
  19. package/dist/types/src/adapters/ProseOl.svelte +7 -0
  20. package/dist/types/src/adapters/ProseP.svelte +7 -0
  21. package/dist/types/src/adapters/ProsePre.svelte +21 -0
  22. package/dist/types/src/adapters/ProseStrong.svelte +7 -0
  23. package/dist/types/src/adapters/ProseTable.svelte +7 -0
  24. package/dist/types/src/adapters/ProseUl.svelte +7 -0
  25. package/dist/types/src/build/access.d.ts +15 -0
  26. package/dist/types/src/build/query.d.ts +8 -4
  27. package/dist/types/src/build/search.d.ts +2 -1
  28. package/dist/types/src/runtime/client.d.ts +2 -1
  29. package/dist/types/src/runtime/query.d.ts +12 -3
  30. package/dist/types/src/server/access.d.ts +4 -0
  31. package/dist/types/src/server/graphql.d.ts +3 -2
  32. package/dist/types/src/server/rest.d.ts +4 -4
  33. package/package.json +8 -8
  34. package/src/build/access.ts +37 -0
  35. package/src/build/api.ts +1 -1
  36. package/src/build/dev.ts +3 -1
  37. package/src/build/graphql.ts +5 -2
  38. package/src/build/query.ts +47 -8
  39. package/src/build/raw.ts +9 -2
  40. package/src/build/search.ts +9 -4
  41. package/src/module.ts +2 -2
  42. package/src/runtime/client.ts +7 -2
  43. package/src/runtime/query.ts +30 -4
  44. package/src/server/access.ts +26 -0
  45. package/src/server/endpoint.ts +3 -2
  46. package/src/server/graphql.ts +13 -6
  47. package/src/server/rest.ts +14 -6
@@ -1,10 +1,14 @@
1
1
  import { type HamurContext } from "hamur/kit";
2
- import type { ContentConfig, ContentOptions } from "../types.ts";
2
+ import type { ContentConfig, ContentEntry, ContentOptions } from "../types.ts";
3
3
  /** `content.clientQuery`, `"local"` by default on the `static` preset, which serves no endpoint. */
4
4
  export declare function resolveClientQuery(value: unknown, preset: string): "api" | "local";
5
- /** `#hamur/content/client`: every collection's name, type, exposure and order; under `"local"` an exposed one imports its chunk, or in `hamur dev` fetches it from `devLoad`'s module. */
6
- export declare function clientModule(config: ContentConfig, mode: "api" | "local", devLoad?: string, raw?: string): string;
5
+ /**
6
+ * `#hamur/content/client`: every collection's name, type, exposure and order; under `"local"` an exposed one imports its chunk, or in
7
+ * `hamur dev` fetches it from `devLoad`'s module. A collection of `asked` has no chunk: the browser asks the endpoint. One of `signed`
8
+ * is marked `basicAuth`: the browser does not query it.
9
+ */
10
+ export declare function clientModule(config: ContentConfig, mode: "api" | "local", devLoad?: string, raw?: string, asked?: ReadonlySet<string>, signed?: ReadonlySet<string>): string;
7
11
  /** The module's one door: `POST /_hamur/content/query` except on `static`, and in `hamur dev` the refresh route. */
8
12
  export declare function doorOf(preset: string, dev: boolean): string;
9
13
  /** The door with `POST /_hamur/content/query` (none on `static`), the store handed to `queryCollection`, and `#hamur/content/client`; with `content.api.rest` the door is generated, and `content.api.graphql` adds the collections' schema. */
10
- export declare function setupQuery(options: ContentOptions, config: ContentConfig, hamur: HamurContext): void;
14
+ export declare function setupQuery(options: ContentOptions, config: ContentConfig, entries: () => Promise<Record<string, ContentEntry[]>>, hamur: HamurContext): void;
@@ -1,3 +1,4 @@
1
+ import { type HamurContext } from "hamur/kit";
1
2
  import { type SearchIndex } from "../runtime/search.ts";
2
3
  import type { ContentConfig, ContentEntry, ContentOptions } from "../types.ts";
3
4
  /** `content.search.collections`, each an exposed page collection of `content.config.ts`. */
@@ -6,4 +7,4 @@ export declare function searchIndexOf(entries: readonly ContentEntry[]): SearchI
6
7
  /** `#hamur/content/search`: each listed collection's index as a lazily imported chunk, which the client bundler hashes; in `hamur dev` fetched from `devLoad`'s module. */
7
8
  export declare function searchModule(names: readonly string[], devLoad?: string): string;
8
9
  /** Returns the collections that get a search index. */
9
- export declare function setupSearch(options: ContentOptions, config: ContentConfig, entries: () => Promise<Record<string, ContentEntry[]>>, dev?: boolean): string[];
10
+ export declare function setupSearch(options: ContentOptions, config: ContentConfig, entries: () => Promise<Record<string, ContentEntry[]>>, hamur: HamurContext): string[];
@@ -1,9 +1,10 @@
1
1
  import type { ContentEntry } from "../types.ts";
2
2
  import { type CollectionQuery, type CollectionQueryBuilder, type QueriedCollection } from "./query.ts";
3
- export declare const QUERY_PATH = "/_hamur/content/query";
4
3
  /** One collection as `#hamur/content/client` lists it; `load` only for an exposed collection under `"local"`. */
5
4
  export interface ClientCollection extends QueriedCollection {
6
5
  expose: boolean;
6
+ /** A page of the collection is under a `basicAuth` rule that the query endpoint does not share. */
7
+ basicAuth?: true;
7
8
  load?: () => Promise<{
8
9
  default: ContentEntry[];
9
10
  }>;
@@ -29,6 +29,8 @@ export interface CollectionQuery {
29
29
  /** A query the engine refuses; the message is the endpoint's 400 text, and the builder puts `queryCollection: ` before it. */
30
30
  export declare class QueryError extends Error {
31
31
  }
32
+ /** The endpoint a browser query posts to, below `app.baseURL`. */
33
+ export declare const QUERY_PATH = "/_hamur/content/query";
32
34
  export declare const QUERY_LIMITS: {
33
35
  readonly conditions: 100;
34
36
  readonly depth: 8;
@@ -48,12 +50,19 @@ export interface QueriedCollection {
48
50
  type: CollectionDefinition["type"];
49
51
  order?: CollectionDefinition["order"];
50
52
  }
53
+ /** What a request from outside may read of a page collection. */
54
+ export interface QueryAccess {
55
+ /** Throws the refusal of the page at `path`. */
56
+ enforce(path: string): Promise<void>;
57
+ /** The entries whose page the request may read; `undefined` for all. */
58
+ visible(entries: readonly ContentEntry[]): Promise<((entry: ContentEntry) => boolean) | undefined>;
59
+ }
51
60
  /** The engine, over one collection's entries in source order. */
52
- export declare function runQuery(name: string, collection: QueriedCollection, entries: readonly ContentEntry[], value: unknown): ContentEntry[] | Record<string, unknown>[] | number;
61
+ export declare function runQuery(name: string, collection: QueriedCollection, entries: readonly ContentEntry[], value: unknown, visible?: (entry: ContentEntry) => boolean): ContentEntry[] | Record<string, unknown>[] | number;
53
62
  /** The server's run of a query: any collection, exposed or not. */
54
63
  export declare function queryStore(store: ContentStore, name: string, query: unknown): Promise<unknown>;
55
- /** What `POST /_hamur/content/query` answers for its body `{ collection, query }`. */
56
- export declare function answerQuery(store: ContentStore, body: unknown): Promise<unknown>;
64
+ /** What `POST /_hamur/content/query` answers for its body `{ collection, query }`; a query for one page by its path is refused as the page is. */
65
+ export declare function answerQuery(store: ContentStore, body: unknown, access?: QueryAccess): Promise<unknown>;
57
66
  /** A field name of a collection or a dotted path that starts with one; `string` while no collection is typed. */
58
67
  export type FieldPath<K extends string = string> = K | `${K}.${string}`;
59
68
  type Where<K extends string> = {
@@ -0,0 +1,4 @@
1
+ import type { HamurEvent } from "hamur/server";
2
+ import type { QueryAccess } from "../runtime/query.ts";
3
+ /** A document of a page collection has the access of its page: what `event` may read of it through the module's own endpoints. */
4
+ export declare const accessFor: (event: HamurEvent) => QueryAccess;
@@ -1,3 +1,4 @@
1
+ import type { HamurEvent } from "hamur/server";
1
2
  import type { CollectionQuery } from "../runtime/query.ts";
2
3
  import type { ContentStore } from "../runtime/store.ts";
3
4
  /** The arguments of `Query.<collection>` in `content.graphql`. */
@@ -17,8 +18,8 @@ export interface ListArgs {
17
18
  /** The arguments as the engine's query: a `value` is read as a REST query value is, and `limit` is capped as REST caps it. */
18
19
  export declare function graphqlQuery({ where, order, limit, skip }: ListArgs): CollectionQuery;
19
20
  /** `Query.<collection>`: the entries the arguments select. */
20
- export declare const contentList: (store: ContentStore, name: string, args: ListArgs) => Promise<unknown>;
21
+ export declare const contentList: (store: ContentStore, name: string, args: ListArgs, event?: HamurEvent) => Promise<unknown>;
21
22
  /** `Query.<collection>Item`: the entry whose `key` (`path` for a page, `id` for data) is `value`, or null. */
22
- export declare function contentItem(store: ContentStore, name: string, key: "path" | "id", value: string): Promise<unknown>;
23
+ export declare function contentItem(store: ContentStore, name: string, key: "path" | "id", value: string, event?: HamurEvent): Promise<unknown>;
23
24
  /** A field with no GraphQL type of its own: its value as JSON text, null when it is missing. */
24
25
  export declare const jsonField: (field: string) => (parent: Record<string, unknown>) => string | null;
@@ -1,4 +1,4 @@
1
- import { type StandardJSONSchemaV1, type StandardSchemaV1 } from "hamur/server";
1
+ import { type HamurEvent, type StandardJSONSchemaV1, type StandardSchemaV1 } from "hamur/server";
2
2
  import { type CollectionQuery, type QueryCondition } from "../runtime/query.ts";
3
3
  import type { ContentStore } from "../runtime/store.ts";
4
4
  /** The most entries one REST answer holds, and its `limit` when none is sent. */
@@ -8,10 +8,10 @@ type DocumentedSchema = StandardSchemaV1<unknown, unknown> & StandardJSONSchemaV
8
8
  export declare function condition(field: string, written: string | undefined, sent: unknown): QueryCondition;
9
9
  /** The query string of `GET /api/_content/<collection>` as the engine's query; `limit` is capped at `REST_LIMIT`. */
10
10
  export declare function restQuery(input: unknown): CollectionQuery;
11
- /** Runs `query` (built by `build`, which may throw a `QueryError`) over an exposed collection: 404 for one the store does not expose, 400 for a query the engine refuses. REST and GraphQL both answer through it. */
12
- export declare function answerExposed(store: ContentStore, name: string, build: () => CollectionQuery): Promise<unknown>;
11
+ /** Runs `query` (built by `build`, which may throw a `QueryError`) over an exposed collection: 404 for one the store does not expose, 400 for a query the engine refuses. REST and GraphQL both answer through it, with the documents `event` may read. */
12
+ export declare function answerExposed(store: ContentStore, name: string, build: () => CollectionQuery, event?: HamurEvent): Promise<unknown>;
13
13
  /** The answer of `GET /api/_content/<name>`. */
14
- export declare const answerRest: (store: ContentStore, name: string, input: unknown) => Promise<unknown>;
14
+ export declare const answerRest: (store: ContentStore, name: string, input: unknown, event?: HamurEvent) => Promise<unknown>;
15
15
  /** `GET /api/_content/<name>` of a name with no route: unknown, or not exposed. */
16
16
  export declare function missingCollection(input: unknown): never;
17
17
  /** The query parameters as OpenAPI lists them; `where[...]` keys have no fixed names, so the operation's description gives them. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hamur/content",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -87,13 +87,13 @@
87
87
  ],
88
88
  "dependencies": {},
89
89
  "peerDependencies": {
90
- "hamur": "^0.0.2",
91
- "@hamur/adapter-react": "^0.0.2",
92
- "@hamur/adapter-vue": "^0.0.2",
93
- "@hamur/adapter-preact": "^0.0.2",
94
- "@hamur/adapter-svelte": "^0.0.2",
95
- "@hamur/adapter-solid": "^0.0.2",
96
- "@hamur/adapter-html": "^0.0.2",
90
+ "hamur": "0.0.4",
91
+ "@hamur/adapter-react": ">=0.0.4 <0.1.0",
92
+ "@hamur/adapter-vue": ">=0.0.4 <0.1.0",
93
+ "@hamur/adapter-preact": ">=0.0.4 <0.1.0",
94
+ "@hamur/adapter-svelte": ">=0.0.4 <0.1.0",
95
+ "@hamur/adapter-solid": ">=0.0.4 <0.1.0",
96
+ "@hamur/adapter-html": ">=0.0.4 <0.1.0",
97
97
  "react": "^19.3.1",
98
98
  "preact": "^11.0.2",
99
99
  "vue": "^3.5.44",
@@ -0,0 +1,37 @@
1
+ import type { HamurContext } from "hamur/kit"
2
+ import { accessRuleOf, hasPlatformFiles } from "hamur/server/internal"
3
+ import { QUERY_PATH } from "../runtime/query.ts"
4
+ import type { ContentEntry, PageEntry } from "../types.ts"
5
+
6
+ export type IsPublic = (entry: ContentEntry, file: string) => boolean
7
+
8
+ /**
9
+ * Whether a build may write what a document says into the public file `file`: its page has no access rule, or the file has the same one
10
+ * and the server runs it. A document of a data collection has no page.
11
+ */
12
+ export function publicIn(hamur: Pick<HamurContext, "options" | "routeRules">): IsPublic {
13
+ const ruleOf = accessRuleOf(hamur.routeRules)
14
+ if (ruleOf.empty) return () => true
15
+ const alone = hasPlatformFiles(hamur)
16
+ return (entry, file) => {
17
+ const { path } = entry as Partial<PageEntry>
18
+ return typeof path !== "string" || ruleOf(path, alone ? undefined : file) === undefined
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Whether a query from the browser cannot read the document: its page is under a `basicAuth` rule that the query endpoint does not
24
+ * share, so a browser that was let in sends no credentials with the query.
25
+ */
26
+ export function signedIn(hamur: Pick<HamurContext, "routeRules">): (entry: ContentEntry) => boolean {
27
+ const ruleOf = accessRuleOf(hamur.routeRules)
28
+ if (ruleOf.empty) return () => false
29
+ return (entry) => {
30
+ const { path } = entry as Partial<PageEntry>
31
+ return typeof path === "string" && ruleOf(path, QUERY_PATH)?.key === "basicAuth"
32
+ }
33
+ }
34
+
35
+ /** A stand-in for the hashed file the client build gives a chunk. */
36
+ export const chunkFile = (hamur: Pick<HamurContext, "options">): string =>
37
+ `/${hamur.options.app.buildAssetsDir.replace(/^\/+|\/+$/g, "")}/content.js`.replace("//", "/")
package/src/build/api.ts CHANGED
@@ -138,7 +138,7 @@ export function restModule(config: ContentConfig, runtime: string): string {
138
138
  " input: restInput,",
139
139
  ` output: restOutput(${q(restSchema(name, config.collections[name]!))}),`,
140
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),`,
141
+ ` handler: (input, { event }) => answerRest(store, ${q(name)}, input, event),`,
142
142
  "});",
143
143
  "",
144
144
  ].join("\n"),
package/src/build/dev.ts CHANGED
@@ -17,6 +17,7 @@ import type {
17
17
  SourceOptions,
18
18
  } from "../types.ts"
19
19
  import { parseRefreshBody } from "../runtime/refresh-body.ts"
20
+ import { chunkFile, publicIn } from "./access.ts"
20
21
  import { DEV_ROUTE, REFRESH_ROUTE } from "./dev-route.ts"
21
22
  import type { ContentIndex } from "./index.ts"
22
23
  import { searchIndexOf } from "./search.ts"
@@ -247,7 +248,8 @@ export function setupDev(
247
248
  const name = match[2]!
248
249
  const collection = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined
249
250
  if (!collection || collection.expose === false || (kind === "search" && !search.includes(name))) return undefined
250
- const entries = (await index.read())[name]!
251
+ const isPublic = publicIn(hamur)
252
+ const entries = (await index.read())[name]!.filter((entry) => isPublic(entry, chunkFile(hamur)))
251
253
  return Response.json(kind === "chunks" ? entries : searchIndexOf(entries), {
252
254
  headers: { "cache-control": "no-store" },
253
255
  })
@@ -132,8 +132,8 @@ export function contentGraphQL(config: ContentConfig, runtime: string): ContentG
132
132
  ` ${name}Item(${key}: String!): ${type}`,
133
133
  )
134
134
  query.push(
135
- ` ${name}: (_parent: unknown, args: ListArgs) => contentList(store, ${q(name)}, args),`,
136
- ` ${name}Item: (_parent: unknown, args: { ${key}: string }) => contentItem(store, ${q(name)}, ${q(key)}, args.${key}),`,
135
+ ` ${name}: (_parent: unknown, args: ListArgs, { event }: Context) => contentList(store, ${q(name)}, args, event),`,
136
+ ` ${name}Item: (_parent: unknown, args: { ${key}: string }, { event }: Context) => contentItem(store, ${q(name)}, ${q(key)}, args.${key}, event),`,
137
137
  )
138
138
  }
139
139
  for (const shared of ["ContentWhere", "ContentOrder", "ContentDirection", "Query"]) {
@@ -171,8 +171,11 @@ export function contentGraphQL(config: ContentConfig, runtime: string): ContentG
171
171
  .map(([name, { json }]) => ` ${name}: { ${json.map((field) => `${field}: jsonField(${q(field)})`).join(", ")} },`)
172
172
  const resolvers = [
173
173
  `import store from "#hamur/content/store";`,
174
+ `import type { HamurEvent } from "hamur/server";`,
174
175
  `import { contentItem, contentList, jsonField, type ListArgs } from ${q(runtime)};`,
175
176
  "",
177
+ "type Context = { event: HamurEvent };",
178
+ "",
176
179
  "export default {",
177
180
  " Query: {",
178
181
  ...query,
@@ -1,5 +1,6 @@
1
1
  import { DiagnosticError, addAppPlugin, addServer, addTemplate, createResolver, type HamurContext } from "hamur/kit"
2
- import type { ContentConfig, ContentOptions } from "../types.ts"
2
+ import type { ContentConfig, ContentEntry, ContentOptions } from "../types.ts"
3
+ import { chunkFile, publicIn, signedIn } from "./access.ts"
3
4
  import { resolveApi, setupRest } from "./api.ts"
4
5
  import { DEV_ROUTE } from "./dev-route.ts"
5
6
  import { setupGraphQL } from "./graphql.ts"
@@ -20,14 +21,30 @@ export function resolveClientQuery(value: unknown, preset: string): "api" | "loc
20
21
  return value
21
22
  }
22
23
 
23
- /** `#hamur/content/client`: every collection's name, type, exposure and order; under `"local"` an exposed one imports its chunk, or in `hamur dev` fetches it from `devLoad`'s module. */
24
- export function clientModule(config: ContentConfig, mode: "api" | "local", devLoad?: string, raw?: string): string {
24
+ /**
25
+ * `#hamur/content/client`: every collection's name, type, exposure and order; under `"local"` an exposed one imports its chunk, or in
26
+ * `hamur dev` fetches it from `devLoad`'s module. A collection of `asked` has no chunk: the browser asks the endpoint. One of `signed`
27
+ * is marked `basicAuth`: the browser does not query it.
28
+ */
29
+ export function clientModule(
30
+ config: ContentConfig,
31
+ mode: "api" | "local",
32
+ devLoad?: string,
33
+ raw?: string,
34
+ asked?: ReadonlySet<string>,
35
+ signed?: ReadonlySet<string>,
36
+ ): string {
25
37
  const collections = Object.entries(config.collections).map(([name, { type, expose = true, order }]) => {
26
- const meta = JSON.stringify({ type, expose, ...(order ? { order } : {}) })
38
+ const meta = JSON.stringify({
39
+ type,
40
+ expose,
41
+ ...(order ? { order } : {}),
42
+ ...(signed?.has(name) ? { basicAuth: true } : {}),
43
+ })
27
44
  const loader = devLoad
28
45
  ? `devLoad(${JSON.stringify(`${DEV_ROUTE}/chunks/${name}.json`)})`
29
46
  : `() => import(${JSON.stringify(`#hamur/content/chunks/${name}.json`)})`
30
- const load = mode === "local" && expose ? `, load: ${loader} }` : ""
47
+ const load = mode === "local" && expose && !asked?.has(name) ? `, load: ${loader} }` : ""
31
48
  return ` ${JSON.stringify(name)}: ${load ? `${meta.slice(0, -1)}${load}` : meta},`
32
49
  })
33
50
  const imports = devLoad && mode === "local" ? [`import { devLoad } from ${JSON.stringify(devLoad)};`, ""] : []
@@ -51,7 +68,12 @@ export function doorOf(preset: string, dev: boolean): string {
51
68
  }
52
69
 
53
70
  /** The door with `POST /_hamur/content/query` (none on `static`), the store handed to `queryCollection`, and `#hamur/content/client`; with `content.api.rest` the door is generated, and `content.api.graphql` adds the collections' schema. */
54
- export function setupQuery(options: ContentOptions, config: ContentConfig, hamur: HamurContext): void {
71
+ export function setupQuery(
72
+ options: ContentOptions,
73
+ config: ContentConfig,
74
+ entries: () => Promise<Record<string, ContentEntry[]>>,
75
+ hamur: HamurContext,
76
+ ): void {
55
77
  const { preset } = hamur.options
56
78
  const mode = resolveClientQuery(options.clientQuery, preset)
57
79
  const client = (hamur.options.build.importProtection.client ??= {})
@@ -64,7 +86,24 @@ export function setupQuery(options: ContentOptions, config: ContentConfig, hamur
64
86
  addAppPlugin({ src: createResolver(import.meta.url).resolve("../runtime/page-plugin.ts"), mode: "all" })
65
87
  addTemplate({
66
88
  filename: "content/client",
67
- getContents: () =>
68
- clientModule(config, mode, devLoad, resolveRaw(options.raw) ? hamur.options.app.baseURL : undefined),
89
+ getContents: async () => {
90
+ const raw = resolveRaw(options.raw) ? hamur.options.app.baseURL : undefined
91
+ if (preset === "static") return clientModule(config, mode, devLoad, raw)
92
+ const all = Object.entries(await entries())
93
+ const names = (test: (entry: ContentEntry) => boolean) =>
94
+ new Set(all.filter(([, list]) => list.some(test)).map(([name]) => name))
95
+ const signed = names(signedIn(hamur))
96
+ if (mode === "api") return clientModule(config, mode, devLoad, raw, undefined, signed)
97
+ const isPublic = publicIn(hamur)
98
+ const file = chunkFile(hamur)
99
+ return clientModule(
100
+ config,
101
+ mode,
102
+ devLoad,
103
+ raw,
104
+ names((entry) => !isPublic(entry, file)),
105
+ signed,
106
+ )
107
+ },
69
108
  })
70
109
  }
package/src/build/raw.ts CHANGED
@@ -2,6 +2,7 @@ import { DiagnosticError, emitPublicAsset, type HamurContext } from "hamur/kit"
2
2
  import { rawPath } from "../runtime/raw-path.ts"
3
3
  import { runQuery, type QueryClause, type QueryCondition } from "../runtime/query.ts"
4
4
  import type { ContentConfig, ContentEntry, ContentOptions, LlmsOptions, PageEntry } from "../types.ts"
5
+ import { publicIn } from "./access.ts"
5
6
  import type { ContentIndex } from "./index.ts"
6
7
 
7
8
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -130,10 +131,12 @@ export function setupRaw(
130
131
  const file = index.file(entry.collection, entry.id)
131
132
  return file === undefined ? undefined : Bun.file(file).text()
132
133
  }
134
+ const isPublic = publicIn(hamur)
133
135
  if (raw) {
134
136
  for (const [name, collection] of Object.entries(config.collections)) {
135
137
  if (collection.type !== "page") continue
136
138
  for (const entry of (entries[name] ?? []) as PageEntry[]) {
139
+ if (!isPublic(entry, rawPath(entry.path))) continue
137
140
  const source = await text(entry)
138
141
  if (source !== undefined) emitPublicAsset(rawPath(entry.path), source)
139
142
  }
@@ -141,12 +144,16 @@ export function setupRaw(
141
144
  }
142
145
  if (llms) {
143
146
  const sections = llmsSections(llms, config, entries)
144
- emitPublicAsset("/llms.txt", llmsText(llms, sections, hamur.options.site.url!, hamur.options.app.baseURL))
147
+ const listed = sections.map(({ title, entries }) => ({
148
+ title,
149
+ entries: entries.filter((entry) => isPublic(entry, "/llms.txt")),
150
+ }))
151
+ emitPublicAsset("/llms.txt", llmsText(llms, listed, hamur.options.site.url!, hamur.options.app.baseURL))
145
152
  const seen = new Set<string>()
146
153
  const sources: string[] = []
147
154
  for (const entry of sections.flatMap((section) => section.entries)) {
148
155
  const key = `${entry.collection}\0${entry.id}`
149
- if (seen.has(key)) continue
156
+ if (seen.has(key) || !isPublic(entry, "/llms-full.txt")) continue
150
157
  seen.add(key)
151
158
  const source = await text(entry)
152
159
  if (source !== undefined) sources.push(source.trimEnd())
@@ -1,7 +1,8 @@
1
- import { DiagnosticError, addAppPlugin, addTemplate, createResolver } from "hamur/kit"
1
+ import { DiagnosticError, addAppPlugin, addTemplate, createResolver, type HamurContext } from "hamur/kit"
2
2
  import { buildSearchIndex, type SearchIndex } from "../runtime/search.ts"
3
3
  import { resolveSectionOptions, sectionsOf, type SearchSection } from "../runtime/sections.ts"
4
4
  import type { ContentConfig, ContentEntry, ContentOptions, PageEntry } from "../types.ts"
5
+ import { chunkFile, publicIn } from "./access.ts"
5
6
  import { DEV_ROUTE } from "./dev-route.ts"
6
7
 
7
8
  /** Code blocks are not indexed: they are a large share of a docs site and mostly noise as search text. */
@@ -48,15 +49,19 @@ export function setupSearch(
48
49
  options: ContentOptions,
49
50
  config: ContentConfig,
50
51
  entries: () => Promise<Record<string, ContentEntry[]>>,
51
- dev = false,
52
+ hamur: HamurContext,
52
53
  ): string[] {
53
54
  const names = resolveSearch(options.search, config)
54
55
  const resolver = createResolver(import.meta.url)
55
- const devLoad = dev ? resolver.resolve("../runtime/dev-client.ts") : undefined
56
+ const devLoad = hamur.options.dev ? resolver.resolve("../runtime/dev-client.ts") : undefined
56
57
  for (const name of names)
57
58
  addTemplate({
58
59
  filename: `content/search-index/${name}.json`,
59
- getContents: async () => JSON.stringify(searchIndexOf((await entries())[name]!)),
60
+ getContents: async () => {
61
+ const isPublic = publicIn(hamur)
62
+ const listed = (await entries())[name]!.filter((entry) => isPublic(entry, chunkFile(hamur)))
63
+ return JSON.stringify(searchIndexOf(listed))
64
+ },
60
65
  })
61
66
  addTemplate({ filename: "content/search", getContents: () => searchModule(names, devLoad) })
62
67
  if (names.length) addAppPlugin({ src: resolver.resolve("../runtime/search-plugin.ts"), mode: "client" })
package/src/module.ts CHANGED
@@ -15,10 +15,10 @@ export default defineModule<ContentOptions>({
15
15
  async setup(options, hamur) {
16
16
  const config = await setupConfig(hamur.options.rootDir)
17
17
  const index = setupIndex(hamur, config, options)
18
- setupQuery(options, config, hamur)
18
+ setupQuery(options, config, index.read, hamur)
19
19
  setupPrerender(options, config, index.read, hamur)
20
20
  setupRaw(options, config, index, hamur)
21
- const search = setupSearch(options, config, index.read, hamur.options.dev)
21
+ const search = setupSearch(options, config, index.read, hamur)
22
22
  setupDev(hamur, config, index, search)
23
23
  setupLive(config, hamur)
24
24
  setupTypes(config, hamur)
@@ -2,6 +2,7 @@ import { $fetch, FetchError } from "hamur/app"
2
2
  import type { ContentEntry } from "../types.ts"
3
3
  import {
4
4
  createQuery,
5
+ QUERY_PATH,
5
6
  QueryError,
6
7
  runQuery,
7
8
  type CollectionQuery,
@@ -9,11 +10,11 @@ import {
9
10
  type QueriedCollection,
10
11
  } from "./query.ts"
11
12
 
12
- export const QUERY_PATH = "/_hamur/content/query"
13
-
14
13
  /** One collection as `#hamur/content/client` lists it; `load` only for an exposed collection under `"local"`. */
15
14
  export interface ClientCollection extends QueriedCollection {
16
15
  expose: boolean
16
+ /** A page of the collection is under a `basicAuth` rule that the query endpoint does not share. */
17
+ basicAuth?: true
17
18
  load?: () => Promise<{ default: ContentEntry[] }>
18
19
  }
19
20
 
@@ -67,6 +68,10 @@ export function createClientQuery(
67
68
  throw new QueryError(
68
69
  `queryCollection(${JSON.stringify(name)}): the collection is not exposed to the client (expose: false)`,
69
70
  )
71
+ if (collection.basicAuth)
72
+ throw new QueryError(
73
+ `queryCollection(${JSON.stringify(name)}): pages of the collection are under basicAuth, whose credentials a browser does not send to ${QUERY_PATH}; query it in a load, which runs on the server for the page's own request`,
74
+ )
70
75
  const { load } = collection
71
76
  if (config.mode === "local" && load)
72
77
  return createQuery<T>(async (query) => runQuery(name, collection, await entries(name, load), query))
@@ -82,6 +82,9 @@ const PAGE_FIELDS = [
82
82
  "readingTime",
83
83
  ]
84
84
 
85
+ /** The endpoint a browser query posts to, below `app.baseURL`. */
86
+ export const QUERY_PATH = "/_hamur/content/query"
87
+
85
88
  export const QUERY_LIMITS = {
86
89
  conditions: 100,
87
90
  depth: 8,
@@ -424,16 +427,35 @@ export interface QueriedCollection {
424
427
  order?: CollectionDefinition["order"]
425
428
  }
426
429
 
430
+ /** What a request from outside may read of a page collection. */
431
+ export interface QueryAccess {
432
+ /** Throws the refusal of the page at `path`. */
433
+ enforce(path: string): Promise<void>
434
+ /** The entries whose page the request may read; `undefined` for all. */
435
+ visible(entries: readonly ContentEntry[]): Promise<((entry: ContentEntry) => boolean) | undefined>
436
+ }
437
+
438
+ /** The path a query asks one page by, as `.path(path)` writes it. */
439
+ function askedPath(query: unknown): string | undefined {
440
+ const where = isRecord(query) && Array.isArray(query.where) ? (query.where as unknown[]) : []
441
+ if (!where.every((clause) => isRecord(clause) && clause.join === "AND")) return undefined
442
+ const clause = where.find((one) => isRecord(one) && one.field === "path" && one.operator === "=") as
443
+ { value?: unknown } | undefined
444
+ return typeof clause?.value === "string" && clause.value.startsWith("/") ? clause.value : undefined
445
+ }
446
+
427
447
  /** The engine, over one collection's entries in source order. */
428
448
  export function runQuery(
429
449
  name: string,
430
450
  collection: QueriedCollection,
431
451
  entries: readonly ContentEntry[],
432
452
  value: unknown,
453
+ visible?: (entry: ContentEntry) => boolean,
433
454
  ): ContentEntry[] | Record<string, unknown>[] | number {
434
455
  const query = checkQuery(value, knownFields(collection.type, entries), name)
435
456
  const where = query.where ?? []
436
- const found = where.length ? entries.filter((entry) => passes(entry, where)) : [...entries]
457
+ const readable = visible ? entries.filter(visible) : entries
458
+ const found = where.length ? readable.filter((entry) => passes(entry, where)) : [...readable]
437
459
  if (query.count) return found.length
438
460
  const order = query.order ?? (collection.order ? [collection.order] : [])
439
461
  const sorted = order.length ? found.sort(sorter(order)) : found
@@ -450,8 +472,8 @@ export async function queryStore(store: ContentStore, name: string, query: unkno
450
472
  return runQuery(name, collection, await store.entries(name), query)
451
473
  }
452
474
 
453
- /** What `POST /_hamur/content/query` answers for its body `{ collection, query }`. */
454
- export async function answerQuery(store: ContentStore, body: unknown): Promise<unknown> {
475
+ /** What `POST /_hamur/content/query` answers for its body `{ collection, query }`; a query for one page by its path is refused as the page is. */
476
+ export async function answerQuery(store: ContentStore, body: unknown, access?: QueryAccess): Promise<unknown> {
455
477
  if (!isRecord(body)) fail("the body must be { collection, query }")
456
478
  const { collection, query, ...rest } = body as Record<string, unknown>
457
479
  for (const key of Object.keys(rest)) fail(`unknown key ${shown(key)}; the body is { collection, query }`)
@@ -461,7 +483,11 @@ export async function answerQuery(store: ContentStore, body: unknown): Promise<u
461
483
  ? store.collections[name]!
462
484
  : fail(`unknown collection ${shown(name)}`)
463
485
  if (!meta.expose) fail(`collection ${shown(name)} is not exposed`)
464
- return runQuery(name, meta, await store.entries(name), query ?? {})
486
+ const entries = await store.entries(name)
487
+ if (!access || meta.type !== "page") return runQuery(name, meta, entries, query ?? {})
488
+ const path = askedPath(query)
489
+ if (path !== undefined) await access.enforce(path)
490
+ return runQuery(name, meta, entries, query ?? {}, await access.visible(entries))
465
491
  }
466
492
 
467
493
  /** A field name of a collection or a dotted path that starts with one; `string` while no collection is typed. */
@@ -0,0 +1,26 @@
1
+ import type { HamurEvent } from "hamur/server"
2
+ import { allowedPaths, requireFileAccess } from "hamur/server/internal"
3
+ import type { ContentEntry, PageEntry } from "../types.ts"
4
+ import type { QueryAccess } from "../runtime/query.ts"
5
+
6
+ const pathOf = (entry: ContentEntry): string | undefined => {
7
+ const { path } = entry as Partial<PageEntry>
8
+ return typeof path === "string" ? path : undefined
9
+ }
10
+
11
+ /** A document of a page collection has the access of its page: what `event` may read of it through the module's own endpoints. */
12
+ export const accessFor = (event: HamurEvent): QueryAccess => ({
13
+ async enforce(path) {
14
+ await requireFileAccess(event, path)
15
+ },
16
+ async visible(entries) {
17
+ const allowed = await allowedPaths(event, () => entries.map(pathOf).filter((path) => path !== undefined))
18
+ return (
19
+ allowed &&
20
+ ((entry) => {
21
+ const path = pathOf(entry)
22
+ return path === undefined || allowed(path)
23
+ })
24
+ )
25
+ },
26
+ })
@@ -1,14 +1,15 @@
1
1
  /// <reference path="../env.d.ts" />
2
2
  import store from "#hamur/content/store"
3
3
  import { createError, defineHandler } from "hamur/server"
4
+ import { accessFor } from "./access.ts"
4
5
  import { answerQuery, QueryError } from "../runtime/query.ts"
5
6
 
6
7
  export const contentQuery = defineHandler({
7
8
  route: "/_hamur/content/query",
8
9
  method: "POST",
9
- async handler(input: unknown) {
10
+ async handler(input: unknown, { event }) {
10
11
  try {
11
- return await answerQuery(store, input)
12
+ return await answerQuery(store, input, accessFor(event))
12
13
  } catch (error) {
13
14
  if (error instanceof QueryError) throw createError({ status: 400, message: error.message })
14
15
  throw error
@@ -1,3 +1,4 @@
1
+ import type { HamurEvent } from "hamur/server"
1
2
  import type { CollectionQuery, QueryClause } from "../runtime/query.ts"
2
3
  import type { ContentStore } from "../runtime/store.ts"
3
4
  import { answerExposed, condition, REST_LIMIT } from "./rest.ts"
@@ -35,8 +36,8 @@ export function graphqlQuery({ where, order, limit, skip }: ListArgs): Collectio
35
36
  }
36
37
 
37
38
  /** `Query.<collection>`: the entries the arguments select. */
38
- export const contentList = (store: ContentStore, name: string, args: ListArgs): Promise<unknown> =>
39
- answerExposed(store, name, () => graphqlQuery(args))
39
+ export const contentList = (store: ContentStore, name: string, args: ListArgs, event?: HamurEvent): Promise<unknown> =>
40
+ answerExposed(store, name, () => graphqlQuery(args), event)
40
41
 
41
42
  /** `Query.<collection>Item`: the entry whose `key` (`path` for a page, `id` for data) is `value`, or null. */
42
43
  export async function contentItem(
@@ -44,11 +45,17 @@ export async function contentItem(
44
45
  name: string,
45
46
  key: "path" | "id",
46
47
  value: string,
48
+ event?: HamurEvent,
47
49
  ): Promise<unknown> {
48
- const found = (await answerExposed(store, name, () => ({
49
- where: [{ join: "AND", field: key, operator: "=", value }],
50
- limit: 1,
51
- }))) as unknown[]
50
+ const found = (await answerExposed(
51
+ store,
52
+ name,
53
+ () => ({
54
+ where: [{ join: "AND", field: key, operator: "=", value }],
55
+ limit: 1,
56
+ }),
57
+ event,
58
+ )) as unknown[]
52
59
  return found[0] ?? null
53
60
  }
54
61