@vllnt/next-llms 0.1.0-canary.e0fc10f → 0.1.0
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/CHANGELOG.md +58 -0
- package/README.md +13 -9
- package/dist/llms-text.d.ts +5 -0
- package/dist/llms-text.d.ts.map +1 -1
- package/dist/llms-text.js +42 -6
- package/dist/llms-text.js.map +1 -1
- package/dist/markdown-route.d.ts +7 -1
- package/dist/markdown-route.d.ts.map +1 -1
- package/dist/markdown-route.js +41 -12
- package/dist/markdown-route.js.map +1 -1
- package/docs/API.md +126 -0
- package/llms.txt +36 -0
- package/package.json +29 -11
- package/src/llms-text.ts +50 -6
- package/src/markdown-route.ts +42 -13
- package/src/index.test.ts +0 -133
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format is based on
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
|
|
5
|
+
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0] - 2026-11-23
|
|
10
|
+
|
|
11
|
+
First stable release. Earlier `0.1.0-canary.*` builds (npm `latest` pointed at
|
|
12
|
+
the oldest one, from 2026-06-17) were prereleases and are superseded by this
|
|
13
|
+
version.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- First stable release of `@vllnt/next-llms`.
|
|
18
|
+
- `generateLlmsText(config)` — generate a spec-compliant `llms.txt` index: an
|
|
19
|
+
`#` title, a `>` blockquote, optional free prose, `## Section` link lists, and
|
|
20
|
+
a droppable `## Optional` section (per the llmstxt.org specification).
|
|
21
|
+
- `createMarkdownRoute(resolver, options?)` — a Web-standard
|
|
22
|
+
`(request) => Promise<Response>` App Router route handler that strips a
|
|
23
|
+
trailing `.md`, resolves the slug, and returns `text/markdown` with a
|
|
24
|
+
`Cache-Control` header (overridable), or `404` when the resolver returns
|
|
25
|
+
`null`.
|
|
26
|
+
- Zero runtime dependencies and no peer dependencies (the package imports
|
|
27
|
+
nothing from `next` or `react`); typed end to end.
|
|
28
|
+
|
|
29
|
+
### Security
|
|
30
|
+
|
|
31
|
+
- `createMarkdownRoute` now answers `400` without calling the resolver when the
|
|
32
|
+
path has malformed percent-encoding (previously an unhandled `URIError`) or a
|
|
33
|
+
decoded segment that is empty, `.`, `..`, or contains `/`, `\` or a NUL byte
|
|
34
|
+
(for example `..%2F..%2Fsecret`), so resolvers that map slugs to files never
|
|
35
|
+
receive a traversal sequence.
|
|
36
|
+
- `createMarkdownRoute` answers `404` when the resolver returns a non-string
|
|
37
|
+
value such as `undefined` (previously an empty `200`), sets
|
|
38
|
+
`X-Content-Type-Options: nosniff`, and throws a `TypeError` at creation for an
|
|
39
|
+
invalid `cacheControl` value instead of failing on every request.
|
|
40
|
+
- `generateLlmsText` collapses line breaks in titles, summaries and notes,
|
|
41
|
+
escapes `[`, `]` and `\` in link titles, percent-encodes whitespace, `(`, `)`,
|
|
42
|
+
`<`, `>` and `\` in URLs, and throws a `TypeError` for blank titles, blank
|
|
43
|
+
URLs, and `javascript:`, `data:` or `vbscript:` URLs, so values cannot inject
|
|
44
|
+
Markdown structure.
|
|
45
|
+
|
|
46
|
+
### Changed
|
|
47
|
+
|
|
48
|
+
- Clarify installation and release channels, document explicit private caching
|
|
49
|
+
for personalized content, and expand the maintained `llms.txt` index.
|
|
50
|
+
- Releases are published only from a `vX.Y.Z` tag on `main` through trusted
|
|
51
|
+
publishing with provenance.
|
|
52
|
+
|
|
53
|
+
### Removed
|
|
54
|
+
|
|
55
|
+
- Relative to the canary builds only: `generateLlmsFullText` and the
|
|
56
|
+
`LlmsFullConfig`, `LlmsFullPage`, and `LlmsFullSection` types are not part of
|
|
57
|
+
the stable API. Use `generateLlmsText` to link to pages served by
|
|
58
|
+
`createMarkdownRoute` instead.
|
package/README.md
CHANGED
|
@@ -52,15 +52,14 @@ in any Next.js runtime (and Remix, Hono, Deno, …).
|
|
|
52
52
|
## Installation
|
|
53
53
|
|
|
54
54
|
```bash
|
|
55
|
-
pnpm add @vllnt/next-llms
|
|
55
|
+
pnpm add @vllnt/next-llms
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
Node.js `>=18`; no peer dependencies
|
|
59
|
-
`
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
removed the older `generateLlmsFullText` API; use the two exports below.
|
|
58
|
+
Node.js `>=18`; no peer dependencies (the package imports nothing from `next` or
|
|
59
|
+
`react`). Every push to `main` can publish a prerelease to the `canary` channel
|
|
60
|
+
(`pnpm add @vllnt/next-llms@canary`); stable releases are published from a
|
|
61
|
+
`vX.Y.Z` tag. The older `generateLlmsFullText` API from early canary builds is
|
|
62
|
+
not part of the stable API; use the two exports below.
|
|
64
63
|
|
|
65
64
|
## Usage
|
|
66
65
|
|
|
@@ -92,8 +91,13 @@ Full reference: [docs/API.md](docs/API.md). Also see the [LLM index](llms.txt),
|
|
|
92
91
|
|
|
93
92
|
- No secrets touched — the package generates text and serves whatever your
|
|
94
93
|
resolver returns.
|
|
95
|
-
- Your resolver is the boundary —
|
|
96
|
-
|
|
94
|
+
- Your resolver is the boundary — authorize the slug before returning content.
|
|
95
|
+
The route rejects malformed percent-encoding and slug segments that are empty,
|
|
96
|
+
`.`, `..`, or contain `/`, `\` or NUL (`400`), but you still own how a slug
|
|
97
|
+
maps to a file or record.
|
|
98
|
+
- `generateLlmsText` escapes link titles and URLs and collapses line breaks, and
|
|
99
|
+
rejects blank titles/URLs and `javascript:`, `data:` or `vbscript:` URLs with
|
|
100
|
+
a `TypeError`.
|
|
97
101
|
- Successful responses default to **public caching** (one hour in browsers, one
|
|
98
102
|
day in shared caches). For private or personalized content, explicitly pass
|
|
99
103
|
`{ cacheControl: "private, no-store" }`; authorization alone does not disable
|
package/dist/llms-text.d.ts
CHANGED
|
@@ -6,6 +6,11 @@ import type { LlmsConfig } from "./types.js";
|
|
|
6
6
|
*
|
|
7
7
|
* @param config - The manifest content.
|
|
8
8
|
* @returns The `llms.txt` file contents (no trailing newline).
|
|
9
|
+
* @throws {TypeError} When a title or link URL is blank, or a URL uses a
|
|
10
|
+
* `javascript:`, `data:` or `vbscript:` scheme. Line breaks inside titles,
|
|
11
|
+
* summaries and notes are collapsed to spaces, `[`, `]` and `\` in link titles
|
|
12
|
+
* are backslash-escaped, and whitespace, `(`, `)`, `<`, `>` and `\` in URLs
|
|
13
|
+
* are percent-encoded, so values cannot inject Markdown structure.
|
|
9
14
|
* @see https://llmstxt.org
|
|
10
15
|
*
|
|
11
16
|
* @example
|
package/dist/llms-text.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llms-text.d.ts","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAyB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"llms-text.d.ts","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAyB,MAAM,YAAY,CAAC;AAqDpE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAU3D"}
|
package/dist/llms-text.js
CHANGED
|
@@ -1,10 +1,41 @@
|
|
|
1
|
+
const UNSAFE_URL_SCHEME = /^(?:javascript|data|vbscript):/i;
|
|
2
|
+
/** UTF-16 code units U+0000 to U+0020 (controls and space), which browsers ignore inside a URL scheme. */
|
|
3
|
+
const SCHEME_NOISE = /[^\u0021-\uFFFF]/g;
|
|
4
|
+
const LINE_BREAKS = /\s*[\n\r\u2028\u2029]+\s*/g;
|
|
5
|
+
/** Percent-encode one character that would end a Markdown link destination. */
|
|
6
|
+
function encodeUrlCharacter(character) {
|
|
7
|
+
if (character === "(")
|
|
8
|
+
return "%28";
|
|
9
|
+
if (character === ")")
|
|
10
|
+
return "%29";
|
|
11
|
+
return encodeURIComponent(character);
|
|
12
|
+
}
|
|
13
|
+
/** Collapse line breaks so a value cannot start a new Markdown block. */
|
|
14
|
+
function singleLine(value) {
|
|
15
|
+
return value.replaceAll(LINE_BREAKS, " ").trim();
|
|
16
|
+
}
|
|
17
|
+
/** Single-line value that must be a non-blank string. */
|
|
18
|
+
function requiredLine(value, label) {
|
|
19
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
20
|
+
throw new TypeError(`${label} must be a non-empty string`);
|
|
21
|
+
}
|
|
22
|
+
return singleLine(value);
|
|
23
|
+
}
|
|
24
|
+
function renderUrl(url) {
|
|
25
|
+
const text = requiredLine(url, "link url");
|
|
26
|
+
if (UNSAFE_URL_SCHEME.test(text.replaceAll(SCHEME_NOISE, ""))) {
|
|
27
|
+
throw new TypeError("link url must not use a javascript:, data: or vbscript: scheme");
|
|
28
|
+
}
|
|
29
|
+
return text.replaceAll(/[\s()<>\\]/g, encodeUrlCharacter);
|
|
30
|
+
}
|
|
1
31
|
function renderLink(link) {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
32
|
+
const title = requiredLine(link.title, "link title").replaceAll(/[[\\\]]/g, String.raw `\$&`);
|
|
33
|
+
const base = `- [${title}](${renderUrl(link.url)})`;
|
|
34
|
+
const notes = link.notes ? singleLine(link.notes) : "";
|
|
35
|
+
return notes ? `${base}: ${notes}` : base;
|
|
5
36
|
}
|
|
6
37
|
function renderSection(section) {
|
|
7
|
-
const heading = `## ${section.title}`;
|
|
38
|
+
const heading = `## ${requiredLine(section.title, "section title")}`;
|
|
8
39
|
const links = section.links.map(renderLink).join("\n");
|
|
9
40
|
return links ? `${heading}\n\n${links}` : heading;
|
|
10
41
|
}
|
|
@@ -15,6 +46,11 @@ function renderSection(section) {
|
|
|
15
46
|
*
|
|
16
47
|
* @param config - The manifest content.
|
|
17
48
|
* @returns The `llms.txt` file contents (no trailing newline).
|
|
49
|
+
* @throws {TypeError} When a title or link URL is blank, or a URL uses a
|
|
50
|
+
* `javascript:`, `data:` or `vbscript:` scheme. Line breaks inside titles,
|
|
51
|
+
* summaries and notes are collapsed to spaces, `[`, `]` and `\` in link titles
|
|
52
|
+
* are backslash-escaped, and whitespace, `(`, `)`, `<`, `>` and `\` in URLs
|
|
53
|
+
* are percent-encoded, so values cannot inject Markdown structure.
|
|
18
54
|
* @see https://llmstxt.org
|
|
19
55
|
*
|
|
20
56
|
* @example
|
|
@@ -30,8 +66,8 @@ function renderSection(section) {
|
|
|
30
66
|
*/
|
|
31
67
|
export function generateLlmsText(config) {
|
|
32
68
|
return [
|
|
33
|
-
`# ${config.title}`,
|
|
34
|
-
...(config.summary ? [`> ${config.summary}`] : []),
|
|
69
|
+
`# ${requiredLine(config.title, "title")}`,
|
|
70
|
+
...(config.summary ? [`> ${singleLine(config.summary)}`] : []),
|
|
35
71
|
...(config.details ? [config.details] : []),
|
|
36
72
|
...(config.sections ?? []).map(renderSection),
|
|
37
73
|
...(config.optional && config.optional.length > 0
|
package/dist/llms-text.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llms-text.js","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAEA,SAAS,
|
|
1
|
+
{"version":3,"file":"llms-text.js","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAEA,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;AAC5D,0GAA0G;AAC1G,MAAM,YAAY,GAAG,mBAAmB,CAAC;AACzC,MAAM,WAAW,GAAG,4BAA4B,CAAC;AAEjD,+EAA+E;AAC/E,SAAS,kBAAkB,CAAC,SAAiB;IAC3C,IAAI,SAAS,KAAK,GAAG;QAAE,OAAO,KAAK,CAAC;IACpC,IAAI,SAAS,KAAK,GAAG;QAAE,OAAO,KAAK,CAAC;IACpC,OAAO,kBAAkB,CAAC,SAAS,CAAC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{ MarkdownResolver, MarkdownRouteOptions } from "./types.js";
|
|
|
9
9
|
* `["docs", "intro"]`).
|
|
10
10
|
* - Returns `200` with `Content-Type: text/markdown; charset=utf-8` and a
|
|
11
11
|
* `Cache-Control` header when the resolver returns a string.
|
|
12
|
-
* - Returns `404` (plain text) when the resolver returns `null
|
|
12
|
+
* - Returns `404` (plain text) when the resolver returns `null` (or any
|
|
13
|
+
* non-string value, such as `undefined` from a missing map entry).
|
|
14
|
+
* - Returns `400` (plain text) without calling the resolver when the path has
|
|
15
|
+
* malformed percent-encoding or a segment that is empty, `.`, `..`, or
|
|
16
|
+
* contains `/`, `\` or a NUL byte.
|
|
17
|
+
* - Sets `X-Content-Type-Options: nosniff` on every response.
|
|
13
18
|
*
|
|
14
19
|
* @param resolver - Maps a slug to its markdown, or `null` when not found.
|
|
15
20
|
* @param options - Optional cache-control override.
|
|
16
21
|
* @returns A route handler suitable for `export const GET = ...`.
|
|
22
|
+
* @throws {TypeError} When `options.cacheControl` is not a valid header value.
|
|
17
23
|
*
|
|
18
24
|
* @example
|
|
19
25
|
* ```ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown-route.d.ts","sourceRoot":"","sources":["../src/markdown-route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"markdown-route.d.ts","sourceRoot":"","sources":["../src/markdown-route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAmCzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,GAAE,oBAAyB,GACjC,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CA6BzC"}
|
package/dist/markdown-route.js
CHANGED
|
@@ -1,18 +1,32 @@
|
|
|
1
1
|
const DEFAULT_CACHE_CONTROL = "public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800";
|
|
2
|
+
const PLAIN_TEXT_HEADERS = {
|
|
3
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
4
|
+
"X-Content-Type-Options": "nosniff",
|
|
5
|
+
};
|
|
2
6
|
/**
|
|
3
7
|
* Decode a URL pathname into slug segments, stripping a trailing `.md` from the
|
|
4
8
|
* last segment. `/docs/intro.md` → `["docs", "intro"]`; `/` → `[]`.
|
|
9
|
+
*
|
|
10
|
+
* Returns `null` when the path cannot name a page safely: malformed
|
|
11
|
+
* percent-encoding, or a decoded segment that is empty, `.`, `..`, or contains
|
|
12
|
+
* `/`, `\` or a NUL byte (so a resolver that maps slugs to files is never
|
|
13
|
+
* handed a traversal sequence such as `..%2F..%2Fsecret`).
|
|
5
14
|
*/
|
|
6
15
|
function pathnameToSlug(pathname) {
|
|
7
|
-
const segments = pathname
|
|
8
|
-
.split("/")
|
|
9
|
-
.filter((segment) => segment.length > 0)
|
|
10
|
-
.map((segment) => decodeURIComponent(segment));
|
|
16
|
+
const segments = pathname.split("/").filter((segment) => segment.length > 0);
|
|
11
17
|
const last = segments.at(-1);
|
|
12
18
|
if (last?.endsWith(".md")) {
|
|
13
19
|
segments[segments.length - 1] = last.slice(0, -3);
|
|
14
20
|
}
|
|
15
|
-
|
|
21
|
+
try {
|
|
22
|
+
const slug = segments.map((segment) => decodeURIComponent(segment));
|
|
23
|
+
return slug.some((segment) => /^\.{0,2}$|[\0/\\]/.test(segment))
|
|
24
|
+
? null
|
|
25
|
+
: slug;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
16
30
|
}
|
|
17
31
|
/**
|
|
18
32
|
* Create a Next.js App Router route handler that serves a slug's markdown
|
|
@@ -24,11 +38,17 @@ function pathnameToSlug(pathname) {
|
|
|
24
38
|
* `["docs", "intro"]`).
|
|
25
39
|
* - Returns `200` with `Content-Type: text/markdown; charset=utf-8` and a
|
|
26
40
|
* `Cache-Control` header when the resolver returns a string.
|
|
27
|
-
* - Returns `404` (plain text) when the resolver returns `null
|
|
41
|
+
* - Returns `404` (plain text) when the resolver returns `null` (or any
|
|
42
|
+
* non-string value, such as `undefined` from a missing map entry).
|
|
43
|
+
* - Returns `400` (plain text) without calling the resolver when the path has
|
|
44
|
+
* malformed percent-encoding or a segment that is empty, `.`, `..`, or
|
|
45
|
+
* contains `/`, `\` or a NUL byte.
|
|
46
|
+
* - Sets `X-Content-Type-Options: nosniff` on every response.
|
|
28
47
|
*
|
|
29
48
|
* @param resolver - Maps a slug to its markdown, or `null` when not found.
|
|
30
49
|
* @param options - Optional cache-control override.
|
|
31
50
|
* @returns A route handler suitable for `export const GET = ...`.
|
|
51
|
+
* @throws {TypeError} When `options.cacheControl` is not a valid header value.
|
|
32
52
|
*
|
|
33
53
|
* @example
|
|
34
54
|
* ```ts
|
|
@@ -42,20 +62,29 @@ function pathnameToSlug(pathname) {
|
|
|
42
62
|
*/
|
|
43
63
|
export function createMarkdownRoute(resolver, options = {}) {
|
|
44
64
|
const cacheControl = options.cacheControl ?? DEFAULT_CACHE_CONTROL;
|
|
65
|
+
// Fail at setup, not on the first request, if the header value is invalid.
|
|
66
|
+
new Headers({ "Cache-Control": cacheControl });
|
|
45
67
|
return async (request) => {
|
|
46
68
|
const slug = pathnameToSlug(new URL(request.url).pathname);
|
|
69
|
+
if (slug === null) {
|
|
70
|
+
return new Response("Bad Request", {
|
|
71
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
72
|
+
status: 400,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
47
75
|
const content = await resolver(slug);
|
|
48
|
-
return content ===
|
|
49
|
-
? new Response(
|
|
50
|
-
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
51
|
-
status: 404,
|
|
52
|
-
})
|
|
53
|
-
: new Response(content, {
|
|
76
|
+
return typeof content === "string"
|
|
77
|
+
? new Response(content, {
|
|
54
78
|
headers: {
|
|
55
79
|
"Cache-Control": cacheControl,
|
|
56
80
|
"Content-Type": "text/markdown; charset=utf-8",
|
|
81
|
+
"X-Content-Type-Options": "nosniff",
|
|
57
82
|
},
|
|
58
83
|
status: 200,
|
|
84
|
+
})
|
|
85
|
+
: new Response("Not Found", {
|
|
86
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
87
|
+
status: 404,
|
|
59
88
|
});
|
|
60
89
|
};
|
|
61
90
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown-route.js","sourceRoot":"","sources":["../src/markdown-route.ts"],"names":[],"mappings":"AAEA,MAAM,qBAAqB,GACzB,qEAAqE,CAAC;AAExE
|
|
1
|
+
{"version":3,"file":"markdown-route.js","sourceRoot":"","sources":["../src/markdown-route.ts"],"names":[],"mappings":"AAEA,MAAM,qBAAqB,GACzB,qEAAqE,CAAC;AAExE,MAAM,kBAAkB,GAAG;IACzB,cAAc,EAAE,2BAA2B;IAC3C,wBAAwB,EAAE,SAAS;CACpC,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,cAAc,CAAC,QAAgB;IACtC,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC7E,MAAM,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7B,IAAI,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,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;gBAC3B,MAAM,EAAE,GAAG;aACZ,CAAC,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
|
package/docs/API.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# API Reference — @vllnt/next-llms
|
|
2
|
+
|
|
3
|
+
**Compatibility:** any Web-standard runtime — Next.js App Router (Edge or Node),
|
|
4
|
+
Remix, Hono, Deno. Node `>=18`. Zero runtime dependencies.
|
|
5
|
+
|
|
6
|
+
See [release channels](../README.md#installation). `generateLlmsFullText` from
|
|
7
|
+
early canary builds is not part of the stable API.
|
|
8
|
+
|
|
9
|
+
All exports are available from the package root:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { generateLlmsText, createMarkdownRoute } from "@vllnt/next-llms";
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## `generateLlmsText(config)`
|
|
18
|
+
|
|
19
|
+
Render an `llms.txt` index manifest from a config object, following the
|
|
20
|
+
[llms.txt specification](https://llmstxt.org).
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
function generateLlmsText(config: LlmsConfig): string;
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Output layout (blocks joined by a blank line, no trailing newline):
|
|
27
|
+
|
|
28
|
+
1. `# {title}` — required H1.
|
|
29
|
+
2. `> {summary}` — blockquote, when `summary` is set.
|
|
30
|
+
3. `{details}` — free-form markdown, when `details` is set.
|
|
31
|
+
4. One `## {section.title}` block per entry in `sections`, each followed by its
|
|
32
|
+
`- [title](url): notes` link list (`: notes` omitted when absent).
|
|
33
|
+
5. A `## Optional` block, when `optional` is a non-empty array.
|
|
34
|
+
|
|
35
|
+
Escaping and validation: line breaks in titles, summary and notes collapse to a
|
|
36
|
+
space; `[`, `]` and `\` in link titles are backslash-escaped; whitespace, `(`,
|
|
37
|
+
`)`, `<`, `>` and `\` in URLs are percent-encoded. A blank `title`, section
|
|
38
|
+
title, link title or link `url`, or a `url` using `javascript:`, `data:` or
|
|
39
|
+
`vbscript:`, throws a `TypeError`. `details` is free-form markdown and is
|
|
40
|
+
emitted unchanged.
|
|
41
|
+
|
|
42
|
+
### `LlmsConfig`
|
|
43
|
+
|
|
44
|
+
| Field | Type | Notes |
|
|
45
|
+
| ---------- | ---------------- | ------------------------------------------------ |
|
|
46
|
+
| `title` | `string` | Required. Rendered as the `#` H1. |
|
|
47
|
+
| `summary` | `string?` | Rendered as a `>` blockquote. |
|
|
48
|
+
| `details` | `string?` | Free-form markdown after the blockquote. |
|
|
49
|
+
| `sections` | `LlmsSection[]?` | Named `## Section` link lists. |
|
|
50
|
+
| `optional` | `LlmsLink[]?` | Links under the droppable `## Optional` section. |
|
|
51
|
+
|
|
52
|
+
`LlmsSection` = `{ title: string; links: LlmsLink[] }`. `LlmsLink` =
|
|
53
|
+
`{ title: string; url: string; notes?: string }`.
|
|
54
|
+
|
|
55
|
+
### Example
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
generateLlmsText({
|
|
59
|
+
title: "Acme Docs",
|
|
60
|
+
summary: "Everything an agent needs to use Acme.",
|
|
61
|
+
sections: [
|
|
62
|
+
{
|
|
63
|
+
title: "Docs",
|
|
64
|
+
links: [{ title: "Quickstart", url: "/docs/quickstart.md" }],
|
|
65
|
+
},
|
|
66
|
+
],
|
|
67
|
+
optional: [{ title: "Changelog", url: "/changelog.md" }],
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## `createMarkdownRoute(resolver, options?)`
|
|
74
|
+
|
|
75
|
+
Create a Next.js App Router route handler that serves a slug's markdown content.
|
|
76
|
+
Mount it at a catch-all route (`app/[...slug]/route.ts`). The handler is a pure
|
|
77
|
+
Web-standard `(request) => Promise<Response>` and imports nothing from `next`.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
function createMarkdownRoute(
|
|
81
|
+
resolver: MarkdownResolver,
|
|
82
|
+
options?: MarkdownRouteOptions,
|
|
83
|
+
): (request: Request) => Promise<Response>;
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`MarkdownResolver` =
|
|
87
|
+
`(slug: string[]) => string | null | Promise<string | null>`. The slug is the
|
|
88
|
+
path segments, URL-decoded, with any trailing `.md` removed.
|
|
89
|
+
|
|
90
|
+
`MarkdownRouteOptions` = `{ cacheControl?: string }`.
|
|
91
|
+
|
|
92
|
+
### Behavior
|
|
93
|
+
|
|
94
|
+
| Request | Resolver returns | Response |
|
|
95
|
+
| ---------------------------- | ---------------- | -------------------------------------------------------------------- |
|
|
96
|
+
| `/docs/intro.md` | `"# Intro…"` | `200`, `Content-Type: text/markdown; charset=utf-8`, `Cache-Control` |
|
|
97
|
+
| `/docs/intro.md` | `""` | `200` with an empty body (empty string is content, not absence) |
|
|
98
|
+
| `/missing.md` | `null` | `404`, `Content-Type: text/plain; charset=utf-8`, body `Not Found` |
|
|
99
|
+
| `/missing.md` | non-string | `404`, same as `null` |
|
|
100
|
+
| `/..%2Fsecret`, `/a%00b` | not called | `400`, `text/plain`, body `Bad Request` |
|
|
101
|
+
| `/docs/getting%20started.md` | — | resolver receives `["docs", "getting started"]` |
|
|
102
|
+
| `/` | — | resolver receives `[]` |
|
|
103
|
+
|
|
104
|
+
A request is rejected with `400` (the resolver is not called) when the path has
|
|
105
|
+
malformed percent-encoding or a decoded segment that is empty, `.`, `..`, or
|
|
106
|
+
contains `/`, `\` or a NUL byte. Every response carries
|
|
107
|
+
`X-Content-Type-Options: nosniff`. An invalid `cacheControl` value throws a
|
|
108
|
+
`TypeError` when the handler is created.
|
|
109
|
+
|
|
110
|
+
Default `Cache-Control`:
|
|
111
|
+
`public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800` — override
|
|
112
|
+
with `options.cacheControl`. For private or personalized responses, explicitly
|
|
113
|
+
use `{ cacheControl: "private, no-store" }` and authorize access in the
|
|
114
|
+
resolver. The public default is not suitable for authenticated content.
|
|
115
|
+
|
|
116
|
+
### Example
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
// app/[...slug]/route.ts
|
|
120
|
+
import { createMarkdownRoute } from "@vllnt/next-llms";
|
|
121
|
+
|
|
122
|
+
export const GET = createMarkdownRoute(
|
|
123
|
+
async (slug) => (await getDoc(slug.join("/")))?.markdown ?? null,
|
|
124
|
+
{ cacheControl: "public, max-age=60" },
|
|
125
|
+
);
|
|
126
|
+
```
|
package/llms.txt
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# @vllnt/next-llms
|
|
2
|
+
|
|
3
|
+
> AI discoverability for Next.js sites — generate llms.txt manifests and serve
|
|
4
|
+
> any page as raw markdown.
|
|
5
|
+
|
|
6
|
+
`@vllnt/next-llms` is a publishable, zero-dependency TypeScript package for
|
|
7
|
+
Next.js (App Router) and any Web-standard runtime. It exposes two functions.
|
|
8
|
+
`generateLlmsText(config)` returns an `llms.txt` index string in the llmstxt.org
|
|
9
|
+
shape — an `#` title, a `>` blockquote, optional free prose, `## Section` link
|
|
10
|
+
lists (`- [title](https://github.com/vllnt/next-llms/blob/main/url): notes`), and a droppable `## Optional` section.
|
|
11
|
+
`createMarkdownRoute(resolver, options?)` returns a Web-standard
|
|
12
|
+
`(request) => Promise<Response>` route handler: it URL-decodes the pathname,
|
|
13
|
+
strips a trailing `.md`, calls the resolver with the slug, and returns `200`
|
|
14
|
+
`text/markdown` with a `Cache-Control` header when the resolver returns a string
|
|
15
|
+
(an empty string is content), or `404` `text/plain` when it returns `null`. The
|
|
16
|
+
handler imports nothing from `next`; `null` is the explicit not-found sentinel.
|
|
17
|
+
|
|
18
|
+
The stable API is the two functions above; the older `generateLlmsFullText`
|
|
19
|
+
API from early canary builds is not included. Install `@vllnt/next-llms`;
|
|
20
|
+
prereleases are on the `canary` tag. Node.js >=18; no peer dependencies.
|
|
21
|
+
Successful responses use public caching by default. Authorize in the resolver and
|
|
22
|
+
set `cacheControl: "private, no-store"` for private/personalized content.
|
|
23
|
+
|
|
24
|
+
## Docs
|
|
25
|
+
|
|
26
|
+
- [README](https://github.com/vllnt/next-llms/blob/main/README.md): Overview, installation, usage examples
|
|
27
|
+
- [API Reference](https://github.com/vllnt/next-llms/blob/main/docs/API.md): Function signatures, config types, response behavior
|
|
28
|
+
- [Changelog](https://github.com/vllnt/next-llms/blob/main/CHANGELOG.md): Version history and release notes
|
|
29
|
+
- [Contributing](https://github.com/vllnt/next-llms/blob/main/CONTRIBUTING.md): Development setup, validation commands, release workflow
|
|
30
|
+
|
|
31
|
+
## Optional
|
|
32
|
+
|
|
33
|
+
- [AGENTS](https://github.com/vllnt/next-llms/blob/main/AGENTS.md): Canonical agent instructions for this repository
|
|
34
|
+
- [Security Policy](https://github.com/vllnt/next-llms/blob/main/SECURITY.md): Vulnerability reporting policy
|
|
35
|
+
- [Code of Conduct](https://github.com/vllnt/next-llms/blob/main/CODE_OF_CONDUCT.md): Community participation guidelines
|
|
36
|
+
- [License](https://github.com/vllnt/next-llms/blob/main/LICENSE): MIT license
|
package/package.json
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vllnt/next-llms",
|
|
3
|
-
"version": "0.1.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "AI discoverability for Next.js sites — generate an llms.txt manifest and serve any page as raw markdown",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"packageManager": "pnpm@
|
|
7
|
+
"packageManager": "pnpm@10.34.8",
|
|
8
8
|
"files": [
|
|
9
9
|
"dist",
|
|
10
|
-
"src"
|
|
10
|
+
"src",
|
|
11
|
+
"docs/API.md",
|
|
12
|
+
"CHANGELOG.md",
|
|
13
|
+
"llms.txt",
|
|
14
|
+
"!src/**/*.test.ts",
|
|
15
|
+
"!src/**/*.spec.*"
|
|
11
16
|
],
|
|
12
17
|
"exports": {
|
|
13
18
|
"./package.json": "./package.json",
|
|
@@ -21,9 +26,9 @@
|
|
|
21
26
|
"main": "./dist/index.js",
|
|
22
27
|
"scripts": {
|
|
23
28
|
"build": "tsc --project ./tsconfig.build.json",
|
|
24
|
-
"typecheck": "tsc --noEmit",
|
|
25
|
-
"typecheck:ci": "tsc --noEmit --project tsconfig.ci.json",
|
|
26
|
-
"lint": "pnpm check:agents && eslint .",
|
|
29
|
+
"typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
|
|
30
|
+
"typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo --project tsconfig.ci.json",
|
|
31
|
+
"lint": "pnpm check:agents && eslint --cache --cache-location node_modules/.cache/eslint/ .",
|
|
27
32
|
"format": "prettier --write .",
|
|
28
33
|
"format:check": "prettier --check .",
|
|
29
34
|
"test": "vitest run --passWithNoTests",
|
|
@@ -33,15 +38,15 @@
|
|
|
33
38
|
"check:agents": "node -e \"const f=require('node:fs');if(!f.existsSync('AGENTS.md')||f.existsSync('CLAUDE.md')||f.existsSync('.claude'))process.exit(1)\""
|
|
34
39
|
},
|
|
35
40
|
"devDependencies": {
|
|
36
|
-
"@types/node": "^
|
|
41
|
+
"@types/node": "^24.19.2",
|
|
37
42
|
"@typescript/native": "npm:typescript@7.0.2",
|
|
38
|
-
"@vitest/coverage-v8": "^
|
|
43
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
39
44
|
"@vllnt/eslint-config": "2.0.0",
|
|
40
45
|
"@vllnt/typescript": "2.0.0",
|
|
41
46
|
"eslint": "^9.0.0",
|
|
42
|
-
"prettier": "^3.
|
|
47
|
+
"prettier": "^3.9.10",
|
|
43
48
|
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
44
|
-
"vitest": "^
|
|
49
|
+
"vitest": "^5.0.5"
|
|
45
50
|
},
|
|
46
51
|
"homepage": "https://github.com/vllnt/next-llms#readme",
|
|
47
52
|
"bugs": {
|
|
@@ -77,5 +82,18 @@
|
|
|
77
82
|
"app-router",
|
|
78
83
|
"markdown",
|
|
79
84
|
"discoverability"
|
|
80
|
-
]
|
|
85
|
+
],
|
|
86
|
+
"pnpm": {
|
|
87
|
+
"minimumReleaseAge": 10080,
|
|
88
|
+
"minimumReleaseAgeExclude": [
|
|
89
|
+
"@vllnt/*"
|
|
90
|
+
],
|
|
91
|
+
"ignoredBuiltDependencies": [
|
|
92
|
+
"esbuild"
|
|
93
|
+
],
|
|
94
|
+
"overrides": {
|
|
95
|
+
"deepmerge-ts@<8.0.0": "8.0.2",
|
|
96
|
+
"handlebars@<4.7.10": "4.7.10"
|
|
97
|
+
}
|
|
98
|
+
}
|
|
81
99
|
}
|
package/src/llms-text.ts
CHANGED
|
@@ -1,13 +1,52 @@
|
|
|
1
1
|
import type { LlmsConfig, LlmsLink, LlmsSection } from "./types.js";
|
|
2
2
|
|
|
3
|
+
const UNSAFE_URL_SCHEME = /^(?:javascript|data|vbscript):/i;
|
|
4
|
+
/** UTF-16 code units U+0000 to U+0020 (controls and space), which browsers ignore inside a URL scheme. */
|
|
5
|
+
const SCHEME_NOISE = /[^\u0021-\uFFFF]/g;
|
|
6
|
+
const LINE_BREAKS = /\s*[\n\r\u2028\u2029]+\s*/g;
|
|
7
|
+
|
|
8
|
+
/** Percent-encode one character that would end a Markdown link destination. */
|
|
9
|
+
function encodeUrlCharacter(character: string): string {
|
|
10
|
+
if (character === "(") return "%28";
|
|
11
|
+
if (character === ")") return "%29";
|
|
12
|
+
return encodeURIComponent(character);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Collapse line breaks so a value cannot start a new Markdown block. */
|
|
16
|
+
function singleLine(value: string): string {
|
|
17
|
+
return value.replaceAll(LINE_BREAKS, " ").trim();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Single-line value that must be a non-blank string. */
|
|
21
|
+
function requiredLine(value: unknown, label: string): string {
|
|
22
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
23
|
+
throw new TypeError(`${label} must be a non-empty string`);
|
|
24
|
+
}
|
|
25
|
+
return singleLine(value);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function renderUrl(url: unknown): string {
|
|
29
|
+
const text = requiredLine(url, "link url");
|
|
30
|
+
if (UNSAFE_URL_SCHEME.test(text.replaceAll(SCHEME_NOISE, ""))) {
|
|
31
|
+
throw new TypeError(
|
|
32
|
+
"link url must not use a javascript:, data: or vbscript: scheme",
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return text.replaceAll(/[\s()<>\\]/g, encodeUrlCharacter);
|
|
36
|
+
}
|
|
37
|
+
|
|
3
38
|
function renderLink(link: LlmsLink): string {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
39
|
+
const title = requiredLine(link.title, "link title").replaceAll(
|
|
40
|
+
/[[\\\]]/g,
|
|
41
|
+
String.raw`\$&`,
|
|
42
|
+
);
|
|
43
|
+
const base = `- [${title}](${renderUrl(link.url)})`;
|
|
44
|
+
const notes = link.notes ? singleLine(link.notes) : "";
|
|
45
|
+
return notes ? `${base}: ${notes}` : base;
|
|
7
46
|
}
|
|
8
47
|
|
|
9
48
|
function renderSection(section: LlmsSection): string {
|
|
10
|
-
const heading = `## ${section.title}`;
|
|
49
|
+
const heading = `## ${requiredLine(section.title, "section title")}`;
|
|
11
50
|
const links = section.links.map(renderLink).join("\n");
|
|
12
51
|
return links ? `${heading}\n\n${links}` : heading;
|
|
13
52
|
}
|
|
@@ -19,6 +58,11 @@ function renderSection(section: LlmsSection): string {
|
|
|
19
58
|
*
|
|
20
59
|
* @param config - The manifest content.
|
|
21
60
|
* @returns The `llms.txt` file contents (no trailing newline).
|
|
61
|
+
* @throws {TypeError} When a title or link URL is blank, or a URL uses a
|
|
62
|
+
* `javascript:`, `data:` or `vbscript:` scheme. Line breaks inside titles,
|
|
63
|
+
* summaries and notes are collapsed to spaces, `[`, `]` and `\` in link titles
|
|
64
|
+
* are backslash-escaped, and whitespace, `(`, `)`, `<`, `>` and `\` in URLs
|
|
65
|
+
* are percent-encoded, so values cannot inject Markdown structure.
|
|
22
66
|
* @see https://llmstxt.org
|
|
23
67
|
*
|
|
24
68
|
* @example
|
|
@@ -34,8 +78,8 @@ function renderSection(section: LlmsSection): string {
|
|
|
34
78
|
*/
|
|
35
79
|
export function generateLlmsText(config: LlmsConfig): string {
|
|
36
80
|
return [
|
|
37
|
-
`# ${config.title}`,
|
|
38
|
-
...(config.summary ? [`> ${config.summary}`] : []),
|
|
81
|
+
`# ${requiredLine(config.title, "title")}`,
|
|
82
|
+
...(config.summary ? [`> ${singleLine(config.summary)}`] : []),
|
|
39
83
|
...(config.details ? [config.details] : []),
|
|
40
84
|
...(config.sections ?? []).map(renderSection),
|
|
41
85
|
...(config.optional && config.optional.length > 0
|
package/src/markdown-route.ts
CHANGED
|
@@ -3,20 +3,34 @@ import type { MarkdownResolver, MarkdownRouteOptions } from "./types.js";
|
|
|
3
3
|
const DEFAULT_CACHE_CONTROL =
|
|
4
4
|
"public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800";
|
|
5
5
|
|
|
6
|
+
const PLAIN_TEXT_HEADERS = {
|
|
7
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
8
|
+
"X-Content-Type-Options": "nosniff",
|
|
9
|
+
};
|
|
10
|
+
|
|
6
11
|
/**
|
|
7
12
|
* Decode a URL pathname into slug segments, stripping a trailing `.md` from the
|
|
8
13
|
* last segment. `/docs/intro.md` → `["docs", "intro"]`; `/` → `[]`.
|
|
14
|
+
*
|
|
15
|
+
* Returns `null` when the path cannot name a page safely: malformed
|
|
16
|
+
* percent-encoding, or a decoded segment that is empty, `.`, `..`, or contains
|
|
17
|
+
* `/`, `\` or a NUL byte (so a resolver that maps slugs to files is never
|
|
18
|
+
* handed a traversal sequence such as `..%2F..%2Fsecret`).
|
|
9
19
|
*/
|
|
10
|
-
function pathnameToSlug(pathname: string): string[] {
|
|
11
|
-
const segments = pathname
|
|
12
|
-
.split("/")
|
|
13
|
-
.filter((segment) => segment.length > 0)
|
|
14
|
-
.map((segment) => decodeURIComponent(segment));
|
|
20
|
+
function pathnameToSlug(pathname: string): string[] | null {
|
|
21
|
+
const segments = pathname.split("/").filter((segment) => segment.length > 0);
|
|
15
22
|
const last = segments.at(-1);
|
|
16
23
|
if (last?.endsWith(".md")) {
|
|
17
24
|
segments[segments.length - 1] = last.slice(0, -3);
|
|
18
25
|
}
|
|
19
|
-
|
|
26
|
+
try {
|
|
27
|
+
const slug = segments.map((segment) => decodeURIComponent(segment));
|
|
28
|
+
return slug.some((segment) => /^\.{0,2}$|[\0/\\]/.test(segment))
|
|
29
|
+
? null
|
|
30
|
+
: slug;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
20
34
|
}
|
|
21
35
|
|
|
22
36
|
/**
|
|
@@ -29,11 +43,17 @@ function pathnameToSlug(pathname: string): string[] {
|
|
|
29
43
|
* `["docs", "intro"]`).
|
|
30
44
|
* - Returns `200` with `Content-Type: text/markdown; charset=utf-8` and a
|
|
31
45
|
* `Cache-Control` header when the resolver returns a string.
|
|
32
|
-
* - Returns `404` (plain text) when the resolver returns `null
|
|
46
|
+
* - Returns `404` (plain text) when the resolver returns `null` (or any
|
|
47
|
+
* non-string value, such as `undefined` from a missing map entry).
|
|
48
|
+
* - Returns `400` (plain text) without calling the resolver when the path has
|
|
49
|
+
* malformed percent-encoding or a segment that is empty, `.`, `..`, or
|
|
50
|
+
* contains `/`, `\` or a NUL byte.
|
|
51
|
+
* - Sets `X-Content-Type-Options: nosniff` on every response.
|
|
33
52
|
*
|
|
34
53
|
* @param resolver - Maps a slug to its markdown, or `null` when not found.
|
|
35
54
|
* @param options - Optional cache-control override.
|
|
36
55
|
* @returns A route handler suitable for `export const GET = ...`.
|
|
56
|
+
* @throws {TypeError} When `options.cacheControl` is not a valid header value.
|
|
37
57
|
*
|
|
38
58
|
* @example
|
|
39
59
|
* ```ts
|
|
@@ -50,22 +70,31 @@ export function createMarkdownRoute(
|
|
|
50
70
|
options: MarkdownRouteOptions = {},
|
|
51
71
|
): (request: Request) => Promise<Response> {
|
|
52
72
|
const cacheControl = options.cacheControl ?? DEFAULT_CACHE_CONTROL;
|
|
73
|
+
// Fail at setup, not on the first request, if the header value is invalid.
|
|
74
|
+
new Headers({ "Cache-Control": cacheControl });
|
|
53
75
|
|
|
54
76
|
return async (request: Request): Promise<Response> => {
|
|
55
77
|
const slug = pathnameToSlug(new URL(request.url).pathname);
|
|
78
|
+
if (slug === null) {
|
|
79
|
+
return new Response("Bad Request", {
|
|
80
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
81
|
+
status: 400,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
56
84
|
const content = await resolver(slug);
|
|
57
85
|
|
|
58
|
-
return content ===
|
|
59
|
-
? new Response(
|
|
60
|
-
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
|
61
|
-
status: 404,
|
|
62
|
-
})
|
|
63
|
-
: new Response(content, {
|
|
86
|
+
return typeof content === "string"
|
|
87
|
+
? new Response(content, {
|
|
64
88
|
headers: {
|
|
65
89
|
"Cache-Control": cacheControl,
|
|
66
90
|
"Content-Type": "text/markdown; charset=utf-8",
|
|
91
|
+
"X-Content-Type-Options": "nosniff",
|
|
67
92
|
},
|
|
68
93
|
status: 200,
|
|
94
|
+
})
|
|
95
|
+
: new Response("Not Found", {
|
|
96
|
+
headers: PLAIN_TEXT_HEADERS,
|
|
97
|
+
status: 404,
|
|
69
98
|
});
|
|
70
99
|
};
|
|
71
100
|
}
|
package/src/index.test.ts
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
|
|
3
|
-
import { createMarkdownRoute, generateLlmsText } from "./index.js";
|
|
4
|
-
|
|
5
|
-
describe("generateLlmsText", () => {
|
|
6
|
-
it("renders a full manifest with summary, details, sections, and Optional", () => {
|
|
7
|
-
const out = generateLlmsText({
|
|
8
|
-
title: "Acme Docs",
|
|
9
|
-
summary: "Everything an agent needs to use Acme.",
|
|
10
|
-
details: "Acme is a widget API.",
|
|
11
|
-
sections: [
|
|
12
|
-
{
|
|
13
|
-
title: "Docs",
|
|
14
|
-
links: [
|
|
15
|
-
{
|
|
16
|
-
title: "Quickstart",
|
|
17
|
-
url: "/docs/quickstart.md",
|
|
18
|
-
notes: "Start here",
|
|
19
|
-
},
|
|
20
|
-
{ title: "Reference", url: "/docs/reference.md" },
|
|
21
|
-
],
|
|
22
|
-
},
|
|
23
|
-
],
|
|
24
|
-
optional: [{ title: "Changelog", url: "/changelog.md" }],
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
expect(out).toBe(
|
|
28
|
-
[
|
|
29
|
-
"# Acme Docs",
|
|
30
|
-
"> Everything an agent needs to use Acme.",
|
|
31
|
-
"Acme is a widget API.",
|
|
32
|
-
"## Docs\n\n- [Quickstart](/docs/quickstart.md): Start here\n- [Reference](/docs/reference.md)",
|
|
33
|
-
"## Optional\n\n- [Changelog](/changelog.md)",
|
|
34
|
-
].join("\n\n"),
|
|
35
|
-
);
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
it("renders a minimal manifest with only a title", () => {
|
|
39
|
-
expect(generateLlmsText({ title: "Bare" })).toBe("# Bare");
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
it("renders a section heading with no links when the link list is empty", () => {
|
|
43
|
-
expect(
|
|
44
|
-
generateLlmsText({
|
|
45
|
-
title: "T",
|
|
46
|
-
sections: [{ title: "Empty", links: [] }],
|
|
47
|
-
}),
|
|
48
|
-
).toBe("# T\n\n## Empty");
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
it("omits the Optional section when optional is an empty array", () => {
|
|
52
|
-
expect(generateLlmsText({ title: "T", optional: [] })).toBe("# T");
|
|
53
|
-
});
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
describe("createMarkdownRoute", () => {
|
|
57
|
-
it("returns 200 markdown with default cache headers when the resolver resolves", async () => {
|
|
58
|
-
const handler = createMarkdownRoute(() => Promise.resolve("# Hello"));
|
|
59
|
-
const response = await handler(
|
|
60
|
-
new Request("https://site.test/docs/intro.md"),
|
|
61
|
-
);
|
|
62
|
-
|
|
63
|
-
expect(response.status).toBe(200);
|
|
64
|
-
expect(response.headers.get("Content-Type")).toBe(
|
|
65
|
-
"text/markdown; charset=utf-8",
|
|
66
|
-
);
|
|
67
|
-
expect(response.headers.get("Cache-Control")).toBe(
|
|
68
|
-
"public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800",
|
|
69
|
-
);
|
|
70
|
-
expect(await response.text()).toBe("# Hello");
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
it("returns 404 plain text when the resolver returns null", async () => {
|
|
74
|
-
const handler = createMarkdownRoute(() => null);
|
|
75
|
-
const response = await handler(new Request("https://site.test/missing.md"));
|
|
76
|
-
|
|
77
|
-
expect(response.status).toBe(404);
|
|
78
|
-
expect(response.headers.get("Content-Type")).toBe(
|
|
79
|
-
"text/plain; charset=utf-8",
|
|
80
|
-
);
|
|
81
|
-
expect(await response.text()).toBe("Not Found");
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
it("honors a custom cacheControl option", async () => {
|
|
85
|
-
const handler = createMarkdownRoute(() => "x", {
|
|
86
|
-
cacheControl: "no-store",
|
|
87
|
-
});
|
|
88
|
-
const response = await handler(new Request("https://site.test/a.md"));
|
|
89
|
-
|
|
90
|
-
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
it("strips a trailing .md and passes the decoded slug to the resolver", async () => {
|
|
94
|
-
let received: string[] = [];
|
|
95
|
-
const handler = createMarkdownRoute((slug) => {
|
|
96
|
-
received = slug;
|
|
97
|
-
return "ok";
|
|
98
|
-
});
|
|
99
|
-
await handler(new Request("https://site.test/docs/getting%20started.md"));
|
|
100
|
-
|
|
101
|
-
expect(received).toEqual(["docs", "getting started"]);
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it("passes a slug without a .md suffix unchanged", async () => {
|
|
105
|
-
let received: string[] = [];
|
|
106
|
-
const handler = createMarkdownRoute((slug) => {
|
|
107
|
-
received = slug;
|
|
108
|
-
return "ok";
|
|
109
|
-
});
|
|
110
|
-
await handler(new Request("https://site.test/docs/intro"));
|
|
111
|
-
|
|
112
|
-
expect(received).toEqual(["docs", "intro"]);
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
it("resolves an empty slug for the root path", async () => {
|
|
116
|
-
let received: string[] = ["unset"];
|
|
117
|
-
const handler = createMarkdownRoute((slug) => {
|
|
118
|
-
received = slug;
|
|
119
|
-
return "root";
|
|
120
|
-
});
|
|
121
|
-
await handler(new Request("https://site.test/"));
|
|
122
|
-
|
|
123
|
-
expect(received).toEqual([]);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
it("treats an empty string as content (200), not a 404", async () => {
|
|
127
|
-
const handler = createMarkdownRoute(() => "");
|
|
128
|
-
const response = await handler(new Request("https://site.test/empty.md"));
|
|
129
|
-
|
|
130
|
-
expect(response.status).toBe(200);
|
|
131
|
-
expect(await response.text()).toBe("");
|
|
132
|
-
});
|
|
133
|
-
});
|