@vllnt/next-llms 0.1.0-canary.78c9be3 → 0.1.0-canary.b0bb621

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/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  # @vllnt/next-llms
8
8
 
9
9
  Make your Next.js site legible to AI agents — generate a spec-compliant
10
- `llms.txt` / `llms-full.txt` manifest and serve any page as raw markdown.
10
+ `llms.txt` manifest and serve any page as raw markdown.
11
11
 
12
12
  ```ts
13
13
  // app/llms.txt/route.ts
@@ -30,18 +30,15 @@ export function GET() {
30
30
  }
31
31
  ```
32
32
 
33
- Emit the `llms.txt` index and its `llms-full.txt` companion, and expose any
34
- page's markdown at `/path.md` so agents skip HTML parsing. Zero runtime
35
- dependencies — pure Web-standard APIs that run in any Next.js runtime (and
36
- Remix, Hono, Deno, …).
33
+ Emit the `llms.txt` index and expose any page's markdown at `/path.md` so agents
34
+ skip HTML parsing. Zero runtime dependencies — pure Web-standard APIs that run
35
+ in any Next.js runtime (and Remix, Hono, Deno, …).
37
36
 
38
37
  ## Features
39
38
 
40
39
  - **Spec-compliant `llms.txt`** — `generateLlmsText` emits the llmstxt.org
41
40
  shape: an `#` title, a `>` blockquote, `## Section` link lists, and a
42
41
  droppable `## Optional` section.
43
- - **`llms-full.txt` companion** — `generateLlmsFullText` inlines every page's
44
- full markdown so an agent reads the whole site in one request.
45
42
  - **Raw-markdown routes** — `createMarkdownRoute` serves any page as
46
43
  `text/markdown`, stripping a trailing `.md` and resolving the slug through
47
44
  your own content source.
@@ -58,7 +55,11 @@ Remix, Hono, Deno, …).
58
55
  pnpm add @vllnt/next-llms
59
56
  ```
60
57
 
61
- No peer dependencies.
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.
62
63
 
63
64
  ## Usage
64
65
 
@@ -80,20 +81,29 @@ with `Content-Type: text/markdown`, or `404` when the resolver returns `null`.
80
81
  | Export | Kind | Result |
81
82
  | ----------------------------------------- | -------- | ----------------------------------------- |
82
83
  | `generateLlmsText(config)` | function | `string` — the `llms.txt` index |
83
- | `generateLlmsFullText(config)` | function | `string` — the `llms-full.txt` bundle |
84
84
  | `createMarkdownRoute(resolver, options?)` | factory | `(request: Request) => Promise<Response>` |
85
85
 
86
- Full reference: [docs/API.md](docs/API.md).
86
+ Full reference: [docs/API.md](docs/API.md). Also see the [LLM index](llms.txt),
87
+ [changelog](CHANGELOG.md), and
88
+ [issue tracker](https://github.com/vllnt/next-llms/issues).
87
89
 
88
90
  ## Security
89
91
 
90
92
  - No secrets touched — the package generates text and serves whatever your
91
93
  resolver returns.
92
- - Your resolver is the boundary — validate and authorize the slug before
93
- returning content.
94
- - Server-controlled cache headers — defaults are safe and overridable per route.
95
-
96
- See [docs/API.md](docs/API.md).
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`.
101
+ - Successful responses default to **public caching** (one hour in browsers, one
102
+ day in shared caches). For private or personalized content, explicitly pass
103
+ `{ cacheControl: "private, no-store" }`; authorization alone does not disable
104
+ caching.
105
+
106
+ See [docs/API.md](docs/API.md) and the [security reporting policy](SECURITY.md).
97
107
 
98
108
  ## Testing
99
109
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- export { generateLlmsFullText } from "./llms-full.js";
2
1
  export { generateLlmsText } from "./llms-text.js";
3
2
  export { createMarkdownRoute } from "./markdown-route.js";
4
- export type { LlmsConfig, LlmsFullConfig, LlmsFullPage, LlmsFullSection, LlmsLink, LlmsSection, MarkdownResolver, MarkdownRouteOptions, } from "./types.js";
3
+ export type { LlmsConfig, LlmsLink, LlmsSection, MarkdownResolver, MarkdownRouteOptions, } from "./types.js";
5
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,YAAY,EACV,UAAU,EACV,cAAc,EACd,YAAY,EACZ,eAAe,EACf,QAAQ,EACR,WAAW,EACX,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,YAAY,EACV,UAAU,EACV,QAAQ,EACR,WAAW,EACX,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- export { generateLlmsFullText } from "./llms-full.js";
2
1
  export { generateLlmsText } from "./llms-text.js";
3
2
  export { createMarkdownRoute } from "./markdown-route.js";
4
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC"}
@@ -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
@@ -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;AAcpE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAU3D"}
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
- return link.notes
3
- ? `- [${link.title}](${link.url}): ${link.notes}`
4
- : `- [${link.title}](${link.url})`;
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
@@ -1 +1 @@
1
- {"version":3,"file":"llms-text.js","sourceRoot":"","sources":["../src/llms-text.ts"],"names":[],"mappings":"AAEA,SAAS,UAAU,CAAC,IAAc;IAChC,OAAO,IAAI,CAAC,KAAK;QACf,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE;QACjD,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC;AACvC,CAAC;AAED,SAAS,aAAa,CAAC,OAAoB;IACzC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACtC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,OAAO,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;AACpD,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAkB;IACjD,OAAO;QACL,KAAK,MAAM,CAAC,KAAK,EAAE;QACnB,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAA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CAAC;IACvD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,OAAO,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;AACpD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAkB;IACjD,OAAO;QACL,KAAK,YAAY,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE;QAC1C,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9D,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,GAAG,CAAC,MAAM,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC;QAC7C,GAAG,CAAC,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC;YAC/C,CAAC,CAAC,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;YAChE,CAAC,CAAC,EAAE,CAAC;KACR,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACjB,CAAC"}
@@ -9,11 +9,17 @@ import type { 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;AAqBzE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,GAAE,oBAAyB,GACjC,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAoBzC"}
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"}
@@ -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
- return segments;
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 === null
49
- ? new Response("Not Found", {
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;;;GAGG;AACH,SAAS,cAAc,CAAC,QAAgB;IACtC,MAAM,QAAQ,GAAG,QAAQ;SACtB,KAAK,CAAC,GAAG,CAAC;SACV,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;SACvC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;IACjD,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,CA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GAAG;aACZ,CAAC,CAAC;QACL,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;QAErC,OAAO,OAAO,OAAO,KAAK,QAAQ;YAChC,CAAC,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE;gBACpB,OAAO,EAAE;oBACP,eAAe,EAAE,YAAY;oBAC7B,cAAc,EAAE,8BAA8B;oBAC9C,wBAAwB,EAAE,SAAS;iBACpC;gBACD,MAAM,EAAE,GAAG;aACZ,CAAC;YACJ,CAAC,CAAC,IAAI,QAAQ,CAAC,WAAW,EAAE;gBACxB,OAAO,EAAE,kBAAkB;gBAC3B,MAAM,EAAE,GAAG;aACZ,CAAC,CAAC;IACT,CAAC,CAAC;AACJ,CAAC"}
package/dist/types.d.ts CHANGED
@@ -39,41 +39,6 @@ export type LlmsConfig = {
39
39
  */
40
40
  optional?: LlmsLink[];
41
41
  };
42
- /**
43
- * A page whose full markdown content goes inline into `llms-full.txt`.
44
- */
45
- export type LlmsFullPage = {
46
- /** Page title, rendered as a `### {title}` heading. */
47
- title: string;
48
- /** Optional source URL, rendered as a `Source: {url}` line under the title. */
49
- url?: string;
50
- /** The page's full markdown content. */
51
- content: string;
52
- };
53
- /**
54
- * A named group of pages in `llms-full.txt`, rendered as a `## {title}` section.
55
- */
56
- export type LlmsFullSection = {
57
- /** Section heading, rendered as `## {title}`. */
58
- title: string;
59
- /** Pages whose content goes inline under the section. */
60
- pages: LlmsFullPage[];
61
- };
62
- /**
63
- * Input for {@link generateLlmsFullText} — the expanded `llms-full.txt` manifest.
64
- *
65
- * @see https://llmstxt.org
66
- */
67
- export type LlmsFullConfig = {
68
- /** Site/project name, rendered as the `# {title}` H1. */
69
- title: string;
70
- /** One-line summary, rendered as a `> {summary}` blockquote. */
71
- summary?: string;
72
- /** Free-form markdown shown after the blockquote. */
73
- details?: string;
74
- /** Sections whose pages go inline in full. */
75
- sections: LlmsFullSection[];
76
- };
77
42
  /**
78
43
  * Maps a route slug to its markdown content, or `null` if there is no page for
79
44
  * the slug. The slug is the path segments with any trailing `.md` stripped.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG;IACrB,gCAAgC;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAC;IACZ,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,iDAAiD;IACjD,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,KAAK,EAAE,QAAQ,EAAE,CAAC;CACnB,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,yDAAyD;IACzD,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC;CACvB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,+EAA+E;IAC/E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,wCAAwC;IACxC,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,iDAAiD;IACjD,KAAK,EAAE,MAAM,CAAC;IACd,yDAAyD;IACzD,KAAK,EAAE,YAAY,EAAE,CAAC;CACvB,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,yDAAyD;IACzD,KAAK,EAAE,MAAM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EAAE,KACX,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAE5C;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC"}
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@vllnt/next-llms",
3
- "version": "0.1.0-canary.78c9be3",
4
- "description": "AI discoverability for Next.js sites — generate llms.txt / llms-full.txt manifests and serve any page as raw markdown",
3
+ "version": "0.1.0-canary.b0bb621",
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@9.15.4",
7
+ "packageManager": "pnpm@10.34.8",
8
8
  "files": [
9
9
  "dist",
10
- "src"
10
+ "src",
11
+ "!src/**/*.test.ts"
11
12
  ],
12
13
  "exports": {
13
14
  "./package.json": "./package.json",
@@ -21,27 +22,27 @@
21
22
  "main": "./dist/index.js",
22
23
  "scripts": {
23
24
  "build": "tsc --project ./tsconfig.build.json",
24
- "typecheck": "tsc --noEmit",
25
- "typecheck:ci": "tsc --noEmit --project tsconfig.ci.json",
26
- "lint": "eslint .",
25
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
26
+ "typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo --project tsconfig.ci.json",
27
+ "lint": "pnpm check:agents && eslint --cache --cache-location node_modules/.cache/eslint/ .",
27
28
  "format": "prettier --write .",
28
29
  "format:check": "prettier --check .",
29
30
  "test": "vitest run --passWithNoTests",
30
31
  "test:watch": "vitest --typecheck --clearScreen false",
31
32
  "test:coverage": "vitest run --coverage --coverage.reporter=text",
32
- "generate:llms": "node scripts/generate-llms.mjs",
33
- "preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck && pnpm generate:llms"
33
+ "preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck",
34
+ "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
35
  },
35
- "dependencies": {},
36
36
  "devDependencies": {
37
- "@types/node": "^20.0.0",
38
- "@vitest/coverage-v8": "^4.1.8",
39
- "@vllnt/eslint-config": "^1.0.0",
40
- "@vllnt/typescript": "^1.0.0",
37
+ "@types/node": "^24.19.2",
38
+ "@typescript/native": "npm:typescript@7.0.2",
39
+ "@vitest/coverage-v8": "^5.0.5",
40
+ "@vllnt/eslint-config": "2.0.0",
41
+ "@vllnt/typescript": "2.0.0",
41
42
  "eslint": "^9.0.0",
42
- "prettier": "^3.4.0",
43
- "typescript": "^5.7.0",
44
- "vitest": "^4.1.8"
43
+ "prettier": "^3.9.10",
44
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
45
+ "vitest": "^5.0.5"
45
46
  },
46
47
  "homepage": "https://github.com/vllnt/next-llms#readme",
47
48
  "bugs": {
@@ -77,5 +78,18 @@
77
78
  "app-router",
78
79
  "markdown",
79
80
  "discoverability"
80
- ]
81
+ ],
82
+ "pnpm": {
83
+ "minimumReleaseAge": 10080,
84
+ "minimumReleaseAgeExclude": [
85
+ "@vllnt/*"
86
+ ],
87
+ "ignoredBuiltDependencies": [
88
+ "esbuild"
89
+ ],
90
+ "overrides": {
91
+ "deepmerge-ts@<8.0.0": "8.0.2",
92
+ "handlebars@<4.7.10": "4.7.10"
93
+ }
94
+ }
81
95
  }
package/src/index.ts CHANGED
@@ -1,11 +1,7 @@
1
- export { generateLlmsFullText } from "./llms-full.js";
2
1
  export { generateLlmsText } from "./llms-text.js";
3
2
  export { createMarkdownRoute } from "./markdown-route.js";
4
3
  export type {
5
4
  LlmsConfig,
6
- LlmsFullConfig,
7
- LlmsFullPage,
8
- LlmsFullSection,
9
5
  LlmsLink,
10
6
  LlmsSection,
11
7
  MarkdownResolver,
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
- return link.notes
5
- ? `- [${link.title}](${link.url}): ${link.notes}`
6
- : `- [${link.title}](${link.url})`;
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
@@ -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
- return segments;
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 === null
59
- ? new Response("Not Found", {
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/types.ts CHANGED
@@ -42,44 +42,6 @@ export type LlmsConfig = {
42
42
  optional?: LlmsLink[];
43
43
  };
44
44
 
45
- /**
46
- * A page whose full markdown content goes inline into `llms-full.txt`.
47
- */
48
- export type LlmsFullPage = {
49
- /** Page title, rendered as a `### {title}` heading. */
50
- title: string;
51
- /** Optional source URL, rendered as a `Source: {url}` line under the title. */
52
- url?: string;
53
- /** The page's full markdown content. */
54
- content: string;
55
- };
56
-
57
- /**
58
- * A named group of pages in `llms-full.txt`, rendered as a `## {title}` section.
59
- */
60
- export type LlmsFullSection = {
61
- /** Section heading, rendered as `## {title}`. */
62
- title: string;
63
- /** Pages whose content goes inline under the section. */
64
- pages: LlmsFullPage[];
65
- };
66
-
67
- /**
68
- * Input for {@link generateLlmsFullText} — the expanded `llms-full.txt` manifest.
69
- *
70
- * @see https://llmstxt.org
71
- */
72
- export type LlmsFullConfig = {
73
- /** Site/project name, rendered as the `# {title}` H1. */
74
- title: string;
75
- /** One-line summary, rendered as a `> {summary}` blockquote. */
76
- summary?: string;
77
- /** Free-form markdown shown after the blockquote. */
78
- details?: string;
79
- /** Sections whose pages go inline in full. */
80
- sections: LlmsFullSection[];
81
- };
82
-
83
45
  /**
84
46
  * Maps a route slug to its markdown content, or `null` if there is no page for
85
47
  * the slug. The slug is the path segments with any trailing `.md` stripped.
@@ -1,14 +0,0 @@
1
- import type { LlmsFullConfig } from "./types.js";
2
- /**
3
- * Generate an `llms-full.txt` manifest — the same header as `llms.txt` followed
4
- * by every page's full markdown content inline, so an agent can read the whole
5
- * site in a single request.
6
- *
7
- * Hierarchy: `# {title}` (site) → `## {section}` → `### {page}` + the page body.
8
- *
9
- * @param config - The manifest content with full page bodies.
10
- * @returns The `llms-full.txt` file contents (no trailing newline).
11
- * @see https://llmstxt.org
12
- */
13
- export declare function generateLlmsFullText(config: LlmsFullConfig): string;
14
- //# sourceMappingURL=llms-full.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"llms-full.d.ts","sourceRoot":"","sources":["../src/llms-full.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAiC,MAAM,YAAY,CAAC;AAehF;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAOnE"}
package/dist/llms-full.js DELETED
@@ -1,31 +0,0 @@
1
- function renderPage(page) {
2
- const head = page.url
3
- ? `### ${page.title}\n\nSource: ${page.url}`
4
- : `### ${page.title}`;
5
- return `${head}\n\n${page.content}`;
6
- }
7
- function renderFullSection(section) {
8
- const heading = `## ${section.title}`;
9
- const pages = section.pages.map(renderPage).join("\n\n");
10
- return pages ? `${heading}\n\n${pages}` : heading;
11
- }
12
- /**
13
- * Generate an `llms-full.txt` manifest — the same header as `llms.txt` followed
14
- * by every page's full markdown content inline, so an agent can read the whole
15
- * site in a single request.
16
- *
17
- * Hierarchy: `# {title}` (site) → `## {section}` → `### {page}` + the page body.
18
- *
19
- * @param config - The manifest content with full page bodies.
20
- * @returns The `llms-full.txt` file contents (no trailing newline).
21
- * @see https://llmstxt.org
22
- */
23
- export function generateLlmsFullText(config) {
24
- return [
25
- `# ${config.title}`,
26
- ...(config.summary ? [`> ${config.summary}`] : []),
27
- ...(config.details ? [config.details] : []),
28
- ...config.sections.map(renderFullSection),
29
- ].join("\n\n");
30
- }
31
- //# sourceMappingURL=llms-full.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"llms-full.js","sourceRoot":"","sources":["../src/llms-full.ts"],"names":[],"mappings":"AAEA,SAAS,UAAU,CAAC,IAAkB;IACpC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG;QACnB,CAAC,CAAC,OAAO,IAAI,CAAC,KAAK,eAAe,IAAI,CAAC,GAAG,EAAE;QAC5C,CAAC,CAAC,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC;IACxB,OAAO,GAAG,IAAI,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;AACtC,CAAC;AAED,SAAS,iBAAiB,CAAC,OAAwB;IACjD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACtC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACzD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,OAAO,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;AACpD,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAsB;IACzD,OAAO;QACL,KAAK,MAAM,CAAC,KAAK,EAAE;QACnB,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAClD,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,iBAAiB,CAAC;KAC1C,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACjB,CAAC"}
package/src/index.test.ts DELETED
@@ -1,184 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import {
4
- createMarkdownRoute,
5
- generateLlmsFullText,
6
- generateLlmsText,
7
- } from "./index.js";
8
-
9
- describe("generateLlmsText", () => {
10
- it("renders a full manifest with summary, details, sections, and Optional", () => {
11
- const out = generateLlmsText({
12
- title: "Acme Docs",
13
- summary: "Everything an agent needs to use Acme.",
14
- details: "Acme is a widget API.",
15
- sections: [
16
- {
17
- title: "Docs",
18
- links: [
19
- {
20
- title: "Quickstart",
21
- url: "/docs/quickstart.md",
22
- notes: "Start here",
23
- },
24
- { title: "Reference", url: "/docs/reference.md" },
25
- ],
26
- },
27
- ],
28
- optional: [{ title: "Changelog", url: "/changelog.md" }],
29
- });
30
-
31
- expect(out).toBe(
32
- [
33
- "# Acme Docs",
34
- "> Everything an agent needs to use Acme.",
35
- "Acme is a widget API.",
36
- "## Docs\n\n- [Quickstart](/docs/quickstart.md): Start here\n- [Reference](/docs/reference.md)",
37
- "## Optional\n\n- [Changelog](/changelog.md)",
38
- ].join("\n\n"),
39
- );
40
- });
41
-
42
- it("renders a minimal manifest with only a title", () => {
43
- expect(generateLlmsText({ title: "Bare" })).toBe("# Bare");
44
- });
45
-
46
- it("renders a section heading with no links when the link list is empty", () => {
47
- expect(
48
- generateLlmsText({
49
- title: "T",
50
- sections: [{ title: "Empty", links: [] }],
51
- }),
52
- ).toBe("# T\n\n## Empty");
53
- });
54
-
55
- it("omits the Optional section when optional is an empty array", () => {
56
- expect(generateLlmsText({ title: "T", optional: [] })).toBe("# T");
57
- });
58
- });
59
-
60
- describe("generateLlmsFullText", () => {
61
- it("inlines page content under sections, with and without source URLs", () => {
62
- const out = generateLlmsFullText({
63
- title: "Acme",
64
- summary: "Full text.",
65
- details: "Intro.",
66
- sections: [
67
- {
68
- title: "Docs",
69
- pages: [
70
- {
71
- title: "Quickstart",
72
- url: "/docs/quickstart",
73
- content: "# QS\n\nDo this.",
74
- },
75
- { title: "Reference", content: "# Ref\n\nDetails." },
76
- ],
77
- },
78
- ],
79
- });
80
-
81
- expect(out).toBe(
82
- [
83
- "# Acme",
84
- "> Full text.",
85
- "Intro.",
86
- "## Docs\n\n### Quickstart\n\nSource: /docs/quickstart\n\n# QS\n\nDo this.\n\n### Reference\n\n# Ref\n\nDetails.",
87
- ].join("\n\n"),
88
- );
89
- });
90
-
91
- it("renders a minimal full manifest (title + empty sections)", () => {
92
- expect(generateLlmsFullText({ title: "Bare", sections: [] })).toBe(
93
- "# Bare",
94
- );
95
- });
96
-
97
- it("renders a section heading with no pages when the page list is empty", () => {
98
- expect(
99
- generateLlmsFullText({
100
- title: "T",
101
- sections: [{ title: "Empty", pages: [] }],
102
- }),
103
- ).toBe("# T\n\n## Empty");
104
- });
105
- });
106
-
107
- describe("createMarkdownRoute", () => {
108
- it("returns 200 markdown with default cache headers when the resolver resolves", async () => {
109
- const handler = createMarkdownRoute(() => Promise.resolve("# Hello"));
110
- const response = await handler(
111
- new Request("https://site.test/docs/intro.md"),
112
- );
113
-
114
- expect(response.status).toBe(200);
115
- expect(response.headers.get("Content-Type")).toBe(
116
- "text/markdown; charset=utf-8",
117
- );
118
- expect(response.headers.get("Cache-Control")).toBe(
119
- "public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800",
120
- );
121
- expect(await response.text()).toBe("# Hello");
122
- });
123
-
124
- it("returns 404 plain text when the resolver returns null", async () => {
125
- const handler = createMarkdownRoute(() => null);
126
- const response = await handler(new Request("https://site.test/missing.md"));
127
-
128
- expect(response.status).toBe(404);
129
- expect(response.headers.get("Content-Type")).toBe(
130
- "text/plain; charset=utf-8",
131
- );
132
- expect(await response.text()).toBe("Not Found");
133
- });
134
-
135
- it("honors a custom cacheControl option", async () => {
136
- const handler = createMarkdownRoute(() => "x", {
137
- cacheControl: "no-store",
138
- });
139
- const response = await handler(new Request("https://site.test/a.md"));
140
-
141
- expect(response.headers.get("Cache-Control")).toBe("no-store");
142
- });
143
-
144
- it("strips a trailing .md and passes the decoded slug to the resolver", async () => {
145
- let received: string[] = [];
146
- const handler = createMarkdownRoute((slug) => {
147
- received = slug;
148
- return "ok";
149
- });
150
- await handler(new Request("https://site.test/docs/getting%20started.md"));
151
-
152
- expect(received).toEqual(["docs", "getting started"]);
153
- });
154
-
155
- it("passes a slug without a .md suffix unchanged", async () => {
156
- let received: string[] = [];
157
- const handler = createMarkdownRoute((slug) => {
158
- received = slug;
159
- return "ok";
160
- });
161
- await handler(new Request("https://site.test/docs/intro"));
162
-
163
- expect(received).toEqual(["docs", "intro"]);
164
- });
165
-
166
- it("resolves an empty slug for the root path", async () => {
167
- let received: string[] = ["unset"];
168
- const handler = createMarkdownRoute((slug) => {
169
- received = slug;
170
- return "root";
171
- });
172
- await handler(new Request("https://site.test/"));
173
-
174
- expect(received).toEqual([]);
175
- });
176
-
177
- it("treats an empty string as content (200), not a 404", async () => {
178
- const handler = createMarkdownRoute(() => "");
179
- const response = await handler(new Request("https://site.test/empty.md"));
180
-
181
- expect(response.status).toBe(200);
182
- expect(await response.text()).toBe("");
183
- });
184
- });
package/src/llms-full.ts DELETED
@@ -1,34 +0,0 @@
1
- import type { LlmsFullConfig, LlmsFullPage, LlmsFullSection } from "./types.js";
2
-
3
- function renderPage(page: LlmsFullPage): string {
4
- const head = page.url
5
- ? `### ${page.title}\n\nSource: ${page.url}`
6
- : `### ${page.title}`;
7
- return `${head}\n\n${page.content}`;
8
- }
9
-
10
- function renderFullSection(section: LlmsFullSection): string {
11
- const heading = `## ${section.title}`;
12
- const pages = section.pages.map(renderPage).join("\n\n");
13
- return pages ? `${heading}\n\n${pages}` : heading;
14
- }
15
-
16
- /**
17
- * Generate an `llms-full.txt` manifest — the same header as `llms.txt` followed
18
- * by every page's full markdown content inline, so an agent can read the whole
19
- * site in a single request.
20
- *
21
- * Hierarchy: `# {title}` (site) → `## {section}` → `### {page}` + the page body.
22
- *
23
- * @param config - The manifest content with full page bodies.
24
- * @returns The `llms-full.txt` file contents (no trailing newline).
25
- * @see https://llmstxt.org
26
- */
27
- export function generateLlmsFullText(config: LlmsFullConfig): string {
28
- return [
29
- `# ${config.title}`,
30
- ...(config.summary ? [`> ${config.summary}`] : []),
31
- ...(config.details ? [config.details] : []),
32
- ...config.sections.map(renderFullSection),
33
- ].join("\n\n");
34
- }