llms-ink 0.1.0 → 0.3.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/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  Turn any link — site, docs section, page, GitHub repo, PDF or video — into llms.txt and llms-full.txt. A typed
4
4
  client for the [llms.ink](https://llms.ink) API with no dependencies. Runs on Node 18+, Bun, Deno, Cloudflare
5
- Workers and browsers.
5
+ Workers and browsers. Also a [Vite plugin, an Astro integration and middleware](#serve-llmstxt-from-your-site) that
6
+ serve llms.txt from your own site.
6
7
 
7
8
  ```sh
8
9
  npm install llms-ink # or: bun add llms-ink
@@ -32,10 +33,11 @@ console.log(report.found, report.summary, report.issues);
32
33
  - `baseUrl`: defaults to `LLMS_INK_API`, else `https://llms.ink`.
33
34
  - `fetch`: a `fetch` to use instead of the global one.
34
35
 
35
- ### `ink.llms(url, { mode?, fresh?, signal? })` → `Promise<Result>`
36
+ ### `ink.llms(url, { mode?, fresh?, native?, signal? })` → `Promise<Result>`
36
37
 
37
38
  `mode` is `'llms'` (default) or `'full'` (up to 20 pages inlined). `fresh: true` skips the cache and rebuilds
38
- (counts against the daily quota). The result:
39
+ (counts against the daily quota). `native: false` always generates the file and never returns the site's own
40
+ llms.txt (by default a site's own file is returned as is, unless llms.ink generated it). The result:
39
41
 
40
42
  ```ts
41
43
  { url, kind, source, mode, title, text, tokens, pages, model, cached, generatedAt, media? }
@@ -50,7 +52,27 @@ Building a big site or a video can take minutes. Bound a call with a signal:
50
52
  ### `ink.check(url, { signal? })` → `Promise<CheckResult>`
51
53
 
52
54
  Checks the site's (or docs section's) published llms.txt against the llmstxt.org format and fetches its first
53
- 25 links: `{ site, url, found, status, title, tokens, sections, links, llmsFull, issues, summary, checkedAt }`.
55
+ 25 links: `{ site, url, found, status, title, tokens, sections, links, llmsFull, parsed, issues, summary, checkedAt }`.
56
+
57
+ `parsed` is the file's structure (`null` when nothing was found):
58
+
59
+ ```ts
60
+ { title, summary, details, sections: [{ name, optional, text, links: [{ title, url, notes, line }] }] }
61
+ ```
62
+
63
+ ### `ink.checkText(text, { base?, links?, signal? })` → `Promise<CheckResult>`
64
+
65
+ Parses and checks llms.txt text you already have, e.g. before publishing it:
66
+
67
+ ```ts
68
+ const { parsed, issues } = await ink.checkText(await readFile('public/llms.txt', 'utf8'), {
69
+ base: 'https://example.com/llms.txt', // resolves relative links; reported as url/site
70
+ links: true, // also fetch up to 25 links and look for llms-full.txt
71
+ });
72
+ ```
73
+
74
+ Without `base`, `site` and `url` are `null`; without `base` and `links`, `llmsFull` is `null` and
75
+ `links.checked` is 0. Up to 2 MB.
54
76
 
55
77
  ### `ink.stream(url, { mode?, fresh?, signal? })` → `AsyncGenerator<StreamEvent>`
56
78
 
@@ -66,6 +88,55 @@ for await (const event of ink.stream('docs.astro.build', { mode: 'full' })) {
66
88
 
67
89
  Breaking out of the loop cancels the request.
68
90
 
91
+ ## Serve llms.txt from your site
92
+
93
+ ### Vite: `llms-ink/vite`
94
+
95
+ ```ts
96
+ // vite.config.ts
97
+ import { defineConfig } from 'vite';
98
+ import { llmsInk } from 'llms-ink/vite';
99
+
100
+ export default defineConfig({ plugins: [llmsInk({ site: 'https://example.com', full: true })] });
101
+ ```
102
+
103
+ After `vite build` (not the dev server or SSR builds), writes `llms.txt` (and `llms-full.txt` with `full`) for
104
+ `site` into `build.outDir`. llms.ink reads the live site, so the files describe the previous deploy. If llms.ink
105
+ fails, the plugin warns and keeps any existing file (e.g. one from `public/`); `strict: true` fails the build.
106
+ Options: `site`, `full`, `key` (default `LLMS_INK_KEY`), `native` (default `true`; a file llms.ink generated before
107
+ is regenerated, not echoed), `strict`, `timeout` (ms, default 300000), `baseUrl`.
108
+
109
+ ### Astro: `llms-ink/astro`
110
+
111
+ ```ts
112
+ // astro.config.mjs
113
+ import { defineConfig } from 'astro/config';
114
+ import llmsInk from 'llms-ink/astro';
115
+
116
+ export default defineConfig({ site: 'https://example.com', integrations: [llmsInk({ full: true })] });
117
+ ```
118
+
119
+ The same, on `astro:build:done`, into the static output. `site` defaults to Astro's `site` plus `base`.
120
+
121
+ ### Middleware: `llms-ink/middleware`
122
+
123
+ ```ts
124
+ import { llmsInkHandler, llmsInkExpress } from 'llms-ink/middleware';
125
+
126
+ const llms = llmsInkHandler({ site: 'https://example.com', markdown: true });
127
+ const response = (await llms(request)) ?? (await app(request)); // Workers, Next.js proxy, Deno, Bun, Hono
128
+
129
+ expressApp.use(llmsInkExpress({ site: 'https://example.com' })); // Express, Connect
130
+ ```
131
+
132
+ Answers `GET`/`HEAD` `/llms.txt` and `/llms-full.txt` from llms.ink, always generated (`native=0`, so it can't
133
+ loop through itself), with llms.ink's `Cache-Control`. Each answer is kept in memory for its `max-age` and served as
134
+ a last good copy (`Warning: 110`, `Cache-Control: max-age=60`) when llms.ink fails. With `markdown: true` it also
135
+ answers `/<page>.md` and requests whose `Accept` prefers `text/markdown` over `text/html` with the page as Markdown.
136
+ Everything else, and llms.ink's own fetcher, gets `undefined` (Express: `next()`). Options: `site`, `key` (default
137
+ `LLMS_INK_KEY`; recommended on shared hosting IPs), `markdown`, `baseUrl`. Don't also ship a static `llms.txt`:
138
+ most hosts serve it before the middleware runs.
139
+
69
140
  ## Errors
70
141
 
71
142
  Every failure is an `LlmsInkError` with `status`, `code`, `title`, `detail`, `errors` (per-parameter issues of
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Astro integration: writes llms.txt (and llms-full.txt) from llms.ink into the build output.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * // astro.config.mjs
7
+ * import { defineConfig } from 'astro/config';
8
+ * import llmsInk from 'llms-ink/astro';
9
+ *
10
+ * export default defineConfig({ site: 'https://example.com', integrations: [llmsInk({ full: true })] });
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import type { AstroIntegration } from 'astro';
16
+ import { type LlmsFilesOptions } from './files.ts';
17
+ /** {@link LlmsFilesOptions} with `site` optional: it defaults to Astro's `site` (plus `base`). */
18
+ export type LlmsInkAstroOptions = Omit<LlmsFilesOptions, 'site'> & {
19
+ site?: string;
20
+ };
21
+ /**
22
+ * After `astro build`, fetches llms.txt — and llms-full.txt with `full: true` — for `site` (default: the
23
+ * `site` and `base` of the Astro config) and writes them into the static output directory. llms.ink reads the
24
+ * live site, so the files describe the previous deploy. When llms.ink can't be reached it warns and keeps any
25
+ * existing file (e.g. one copied from `public/`); `strict: true` fails the build instead.
26
+ */
27
+ export declare function llmsInk(options?: LlmsInkAstroOptions): AstroIntegration;
28
+ export default llmsInk;
package/dist/astro.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Astro integration: writes llms.txt (and llms-full.txt) from llms.ink into the build output.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * // astro.config.mjs
7
+ * import { defineConfig } from 'astro/config';
8
+ * import llmsInk from 'llms-ink/astro';
9
+ *
10
+ * export default defineConfig({ site: 'https://example.com', integrations: [llmsInk({ full: true })] });
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import { fileURLToPath } from 'node:url';
16
+ import { llmsFilesWriter } from "./files.js";
17
+ /**
18
+ * After `astro build`, fetches llms.txt — and llms-full.txt with `full: true` — for `site` (default: the
19
+ * `site` and `base` of the Astro config) and writes them into the static output directory. llms.ink reads the
20
+ * live site, so the files describe the previous deploy. When llms.ink can't be reached it warns and keeps any
21
+ * existing file (e.g. one copied from `public/`); `strict: true` fails the build instead.
22
+ */
23
+ export function llmsInk(options = {}) {
24
+ const settings = { ...options, site: options.site ?? '' };
25
+ const write = llmsFilesWriter(settings);
26
+ return {
27
+ name: 'llms-ink',
28
+ hooks: {
29
+ 'astro:config:done': ({ config }) => {
30
+ if (!settings.site && config.site)
31
+ settings.site = new URL(config.base, config.site).href;
32
+ },
33
+ 'astro:build:done': async ({ dir, logger }) => {
34
+ await write(fileURLToPath(dir), logger);
35
+ },
36
+ },
37
+ };
38
+ }
39
+ export default llmsInk;
package/dist/env.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** `process.env[name]` where there is a `process` (Node, Bun, Deno with env access); undefined elsewhere. */
2
+ export declare function env(name: string): string | undefined;
package/dist/env.js ADDED
@@ -0,0 +1,11 @@
1
+ /** `process.env[name]` where there is a `process` (Node, Bun, Deno with env access); undefined elsewhere. */
2
+ export function env(name) {
3
+ // Read off globalThis, not a declared global, so it neither needs nor clashes with @types/node.
4
+ const scope = globalThis;
5
+ try {
6
+ return scope.process?.env?.[name]?.trim() || undefined;
7
+ }
8
+ catch {
9
+ return undefined; // Deno without --allow-env throws
10
+ }
11
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Shared by the Vite plugin and the Astro integration: fetch llms.txt (and llms-full.txt) for a site and write
3
+ * them into a build's output directory.
4
+ *
5
+ * @module
6
+ */
7
+ /** Options for the Vite plugin and the Astro integration. */
8
+ export interface LlmsFilesOptions {
9
+ /** The deployed site to describe, e.g. `https://example.com`. llms.ink reads the live site. */
10
+ site: string;
11
+ /** Also write llms-full.txt (the content of up to 20 pages). Default `false`. */
12
+ full?: boolean;
13
+ /** API key (`lk_…`). Defaults to the `LLMS_INK_KEY` environment variable; anonymous without one. */
14
+ key?: string;
15
+ /**
16
+ * Default `true`: when the live site publishes its own llms.txt, that file is used as is, unless it's one
17
+ * llms.ink generated before (it carries the llms.ink credit line), which is regenerated. `false` always
18
+ * generates (`native=0`).
19
+ */
20
+ native?: boolean;
21
+ /** Fail the build when a file can't be fetched. Default `false`: warn and keep any existing file. */
22
+ strict?: boolean;
23
+ /** Milliseconds to wait for llms.ink per file. Default 300000 (building a big site can take minutes). */
24
+ timeout?: number;
25
+ /** Defaults to the `LLMS_INK_API` environment variable, else https://llms.ink. */
26
+ baseUrl?: string;
27
+ }
28
+ /** Where messages go: Vite's or Astro's logger. */
29
+ export interface Log {
30
+ info(message: string): void;
31
+ warn(message: string): void;
32
+ }
33
+ /**
34
+ * A writer that fetches the files once and writes them into `dir` on every call (watch builds call it again;
35
+ * a failed fetch is retried on the next call).
36
+ */
37
+ export declare function llmsFilesWriter(options: LlmsFilesOptions): (dir: string, log: Log) => Promise<void>;
package/dist/files.js ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Shared by the Vite plugin and the Astro integration: fetch llms.txt (and llms-full.txt) for a site and write
3
+ * them into a build's output directory.
4
+ *
5
+ * @module
6
+ */
7
+ import { access, mkdir, writeFile } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import { LlmsInk } from "./index.js";
10
+ const FILES = [['llms.txt', 'llms'], ['llms-full.txt', 'full']];
11
+ /**
12
+ * A writer that fetches the files once and writes them into `dir` on every call (watch builds call it again;
13
+ * a failed fetch is retried on the next call).
14
+ */
15
+ export function llmsFilesWriter(options) {
16
+ let fetched;
17
+ return async (dir, log) => {
18
+ const { site, strict = false } = options;
19
+ if (!site) {
20
+ const message = 'No `site` set: llms.txt not written.';
21
+ if (strict)
22
+ throw new Error(message);
23
+ return log.warn(message);
24
+ }
25
+ fetched ??= fetchFiles(options);
26
+ const results = await fetched;
27
+ const failures = [];
28
+ for (const result of results) {
29
+ const path = join(dir, result.name);
30
+ if ('text' in result) {
31
+ await mkdir(dir, { recursive: true });
32
+ await writeFile(path, result.text);
33
+ log.info(`Wrote ${result.name} for ${site} (${result.source}, ~${result.tokens} tokens).`);
34
+ continue;
35
+ }
36
+ const reason = result.error instanceof Error ? result.error.message : String(result.error);
37
+ const kept = await access(path).then(() => 'kept the existing file', () => 'none written');
38
+ failures.push(`Couldn't get ${result.name} for ${site}: ${reason} (${kept}).`);
39
+ }
40
+ if (failures.length)
41
+ fetched = undefined;
42
+ if (strict && failures.length)
43
+ throw new Error(failures.join(' '));
44
+ for (const message of failures)
45
+ log.warn(message);
46
+ };
47
+ }
48
+ async function fetchFiles({ site, full, key, native = true, timeout = 300_000, baseUrl }) {
49
+ const ink = new LlmsInk({ key, baseUrl });
50
+ const files = full ? FILES : FILES.slice(0, 1);
51
+ return Promise.all(files.map(([name, mode]) => ink.llms(site, { mode, native, signal: AbortSignal.timeout(timeout) }).then(({ text, tokens, source }) => ({ name, text, tokens, source }), (error) => ({ name, error }))));
52
+ }
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * @module
15
15
  */
16
- export declare const VERSION = "0.1.0";
16
+ export declare const VERSION = "0.3.0";
17
17
  export declare const DEFAULT_BASE_URL = "https://llms.ink";
18
18
  /** `llms` for the index (llms.txt), `full` for llms-full.txt. */
19
19
  export type Mode = 'llms' | 'full';
@@ -72,12 +72,40 @@ export interface CheckIssue {
72
72
  line: number | null;
73
73
  message: string;
74
74
  }
75
- /** `GET /api/v0/check`: a published llms.txt checked against the format and its links. */
76
- export interface CheckResult {
77
- /** The site's origin. */
78
- site: string;
79
- /** The llms.txt that was checked (or the last place looked when none was found). */
75
+ /** One link of a section: `- [title](url): notes`. */
76
+ export interface ParsedLink {
77
+ title: string;
78
+ /** Resolved against `base` / the fetched URL when possible, else as written. */
80
79
  url: string;
80
+ /** Text after `:`, trimmed. */
81
+ notes: string | null;
82
+ line: number;
83
+ }
84
+ /** An H2 section of llms.txt. */
85
+ export interface ParsedSection {
86
+ name: string;
87
+ /** The section is named "Optional" (case-insensitive). */
88
+ optional: boolean;
89
+ /** Non-link content of the section. */
90
+ text: string | null;
91
+ links: ParsedLink[];
92
+ }
93
+ /** The structure of an llms.txt file. */
94
+ export interface ParsedLlms {
95
+ /** The H1. */
96
+ title: string | null;
97
+ /** The blockquote, without `> `. */
98
+ summary: string | null;
99
+ /** Markdown between the summary and the first H2. */
100
+ details: string | null;
101
+ sections: ParsedSection[];
102
+ }
103
+ /** `GET` / `POST /api/v0/check`: an llms.txt checked against the format and its links. */
104
+ export interface CheckResult {
105
+ /** The site's origin; null for {@link LlmsInk.checkText} without `base`. */
106
+ site: string | null;
107
+ /** The llms.txt that was checked (or the last place looked when none was found); null for text without `base`. */
108
+ url: string | null;
81
109
  found: boolean;
82
110
  /** HTTP status of the llms.txt request. */
83
111
  status: number;
@@ -87,7 +115,7 @@ export interface CheckResult {
87
115
  sections: number;
88
116
  links: {
89
117
  total: number;
90
- /** Links fetched this run (the first 25). */
118
+ /** Links fetched this run (the first 25); 0 when links weren't checked. */
91
119
  checked: number;
92
120
  /** `status` is 0 when the link didn't answer in time. */
93
121
  broken: Array<{
@@ -95,8 +123,10 @@ export interface CheckResult {
95
123
  status: number;
96
124
  }>;
97
125
  };
98
- /** Whether llms-full.txt is published next to it. */
99
- llmsFull: boolean;
126
+ /** Whether llms-full.txt is published next to it; null when not checked. */
127
+ llmsFull: boolean | null;
128
+ /** The parsed file; null when nothing was found. */
129
+ parsed: ParsedLlms | null;
100
130
  /** Errors first, then warnings and notes, in line order. */
101
131
  issues: CheckIssue[];
102
132
  summary: {
@@ -107,7 +137,7 @@ export interface CheckResult {
107
137
  checkedAt: string;
108
138
  }
109
139
  /** Every error code the API answers with (https://llms.ink/docs/#errors). */
110
- export type ErrorCode = 'invalid_request' | 'invalid_url' | 'invalid_key' | 'not_found' | 'unknown_version' | 'method_not_allowed' | 'payload_too_large' | 'unprocessable' | 'rate_limited' | 'quota_exceeded' | 'internal' | 'upstream_error' | 'unavailable' | 'timeout';
140
+ export type ErrorCode = 'invalid_request' | 'invalid_url' | 'invalid_key' | 'not_found' | 'unknown_version' | 'method_not_allowed' | 'payload_too_large' | 'unprocessable' | 'rate_limited' | 'quota_exceeded' | 'internal' | 'upstream_error' | 'unavailable' | 'timeout' | 'loop_detected';
111
141
  /** `invalid_request` only: one invalid parameter. */
112
142
  export interface Issue {
113
143
  path: string;
@@ -193,6 +223,12 @@ export interface LlmsOptions {
193
223
  mode?: Mode;
194
224
  /** Skip the cache and rebuild (counts against the daily quota). */
195
225
  fresh?: boolean;
226
+ /**
227
+ * `false` always generates the file from the site's pages and never returns the site's own llms.txt or
228
+ * llms-full.txt (`native=0`). Defaults to `true`: a site's own file is returned as is, unless it carries the
229
+ * llms.ink credit line (then it's regenerated).
230
+ */
231
+ native?: boolean;
196
232
  /** Aborts the request; the abort error is rethrown as is. */
197
233
  signal?: AbortSignal;
198
234
  }
@@ -200,6 +236,14 @@ export interface LlmsOptions {
200
236
  export interface CheckOptions {
201
237
  signal?: AbortSignal;
202
238
  }
239
+ /** Options for {@link LlmsInk.checkText}. */
240
+ export interface CheckTextOptions {
241
+ /** Public URL the text lives at: resolves relative links and is reported as `url` / `site`. */
242
+ base?: string;
243
+ /** Also check up to 25 linked URLs (and llms-full.txt next to `base`). Defaults to `false`. */
244
+ links?: boolean;
245
+ signal?: AbortSignal;
246
+ }
203
247
  /**
204
248
  * A client for https://llms.ink.
205
249
  *
@@ -220,6 +264,8 @@ export declare class LlmsInk {
220
264
  llms(url: string, options?: LlmsOptions): Promise<Result>;
221
265
  /** Checks a site's published llms.txt against the llmstxt.org format and that its links answer. */
222
266
  check(url: string, options?: CheckOptions): Promise<CheckResult>;
267
+ /** Parses and checks llms.txt text you already have (`POST /api/v0/check`); nothing is published. */
268
+ checkText(text: string, options?: CheckTextOptions): Promise<CheckResult>;
223
269
  /**
224
270
  * Like {@link LlmsInk.llms}, as the build happens: yields `progress` and `partial` events, then one
225
271
  * `result`. Errors — including a terminal `error` event — are thrown as {@link LlmsInkError}s.
package/dist/index.js CHANGED
@@ -13,7 +13,8 @@
13
13
  *
14
14
  * @module
15
15
  */
16
- export const VERSION = '0.1.0';
16
+ import { env } from "./env.js";
17
+ export const VERSION = '0.3.0';
17
18
  export const DEFAULT_BASE_URL = 'https://llms.ink';
18
19
  /**
19
20
  * An API error, or llms.ink couldn't be reached (then `status` and `code` are undefined).
@@ -57,15 +58,6 @@ const BY_CODE = {
57
58
  quota_exceeded: QuotaExceededError,
58
59
  };
59
60
  const errorFor = (detail, init) => new (BY_CODE[init.code ?? ''] ?? LlmsInkError)(detail, init);
60
- /** `process.env[name]` where there is a `process` (Node, Bun, Deno with env access); undefined elsewhere. */
61
- function env(name) {
62
- try {
63
- return (typeof process === 'undefined' ? undefined : process.env?.[name]?.trim()) || undefined;
64
- }
65
- catch {
66
- return undefined; // Deno without --allow-env throws
67
- }
68
- }
69
61
  /** Browsers refuse or preflight a custom User-Agent, so it's only sent from servers. */
70
62
  const IS_BROWSER = 'document' in globalThis || 'WorkerGlobalScope' in globalThis;
71
63
  /** `Retry-After` as seconds: delta-seconds, or an HTTP date turned into seconds from now. */
@@ -107,12 +99,22 @@ export class LlmsInk {
107
99
  * any public link.
108
100
  */
109
101
  async llms(url, options = {}) {
110
- const res = await this.#get('/api/v0/llms', llmsParams(url, options), 'application/json', options.signal);
102
+ const res = await this.#request('/api/v0/llms', llmsParams(url, options), 'application/json', options.signal);
111
103
  return (await this.#json(res));
112
104
  }
113
105
  /** Checks a site's published llms.txt against the llmstxt.org format and that its links answer. */
114
106
  async check(url, options = {}) {
115
- const res = await this.#get('/api/v0/check', { url }, 'application/json', options.signal);
107
+ const res = await this.#request('/api/v0/check', { url }, 'application/json', options.signal);
108
+ return (await this.#json(res));
109
+ }
110
+ /** Parses and checks llms.txt text you already have (`POST /api/v0/check`); nothing is published. */
111
+ async checkText(text, options = {}) {
112
+ const params = {};
113
+ if (options.base)
114
+ params.base = options.base;
115
+ if (options.links)
116
+ params.links = '1';
117
+ const res = await this.#request('/api/v0/check', params, 'application/json', options.signal, text);
116
118
  return (await this.#json(res));
117
119
  }
118
120
  /**
@@ -121,7 +123,7 @@ export class LlmsInk {
121
123
  * Breaking out of the loop cancels the request.
122
124
  */
123
125
  async *stream(url, options = {}) {
124
- const res = await this.#get('/api/v0/llms', llmsParams(url, options), 'application/x-ndjson', options.signal);
126
+ const res = await this.#request('/api/v0/llms', llmsParams(url, options), 'application/x-ndjson', options.signal);
125
127
  if (!res.headers.get('content-type')?.includes('ndjson')) {
126
128
  yield { type: 'result', result: (await this.#json(res)) };
127
129
  return;
@@ -181,16 +183,19 @@ export class LlmsInk {
181
183
  const known = event.type === 'progress' || event.type === 'partial' || event.type === 'result';
182
184
  return known ? event : undefined;
183
185
  }
184
- async #get(path, params, accept, signal) {
186
+ async #request(path, params, accept, signal, body) {
185
187
  const headers = { accept };
188
+ if (body !== undefined)
189
+ headers['content-type'] = 'text/markdown; charset=utf-8';
186
190
  if (!IS_BROWSER)
187
191
  headers['user-agent'] = `llms-ink-js/${VERSION}`;
188
192
  if (this.key)
189
193
  headers.authorization = `Bearer ${this.key}`;
190
- const target = `${this.baseUrl}${path}?${new URLSearchParams(params)}`;
194
+ const query = new URLSearchParams(params).toString();
195
+ const target = `${this.baseUrl}${path}${query ? `?${query}` : ''}`;
191
196
  let res;
192
197
  try {
193
- res = await this.#fetch(target, { headers, signal });
198
+ res = await this.#fetch(target, body === undefined ? { headers, signal } : { method: 'POST', headers, body, signal });
194
199
  }
195
200
  catch (err) {
196
201
  if (isAbort(err))
@@ -211,11 +216,16 @@ export class LlmsInk {
211
216
  }
212
217
  }
213
218
  }
214
- function llmsParams(url, { mode = 'llms', fresh }) {
219
+ function llmsParams(url, { mode = 'llms', fresh, native = true }) {
215
220
  if (mode !== 'llms' && mode !== 'full') {
216
221
  throw new TypeError(`mode must be 'llms' (the index) or 'full' (llms-full.txt), not ${JSON.stringify(mode)}`);
217
222
  }
218
- return fresh ? { url, mode, fresh: '1' } : { url, mode };
223
+ const params = { url, mode };
224
+ if (fresh)
225
+ params.fresh = '1';
226
+ if (!native)
227
+ params.native = '0';
228
+ return params;
219
229
  }
220
230
  /** An HTTP error response → the typed error for its problem `code`. */
221
231
  async function problem(res) {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Serve llms.txt, llms-full.txt and (optionally) Markdown versions of pages from llms.ink, inside your own app.
3
+ * A fetch-API handler for Cloudflare Workers, Next.js middleware, Deno, Bun and Hono, plus an Express/Connect
4
+ * adapter.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { llmsInkHandler } from 'llms-ink/middleware';
9
+ *
10
+ * const llms = llmsInkHandler({ site: 'https://example.com', markdown: true });
11
+ * export default {
12
+ * async fetch(request: Request): Promise<Response> {
13
+ * return (await llms(request)) ?? fetch(request); // undefined: not ours, the app answers
14
+ * },
15
+ * };
16
+ * ```
17
+ *
18
+ * @module
19
+ */
20
+ /** Options for {@link llmsInkHandler} and {@link llmsInkExpress}. */
21
+ export interface LlmsInkHandlerOptions {
22
+ /** The deployed site to describe, e.g. `https://example.com`. */
23
+ site: string;
24
+ /**
25
+ * API key (`lk_…`), sent as `Authorization: Bearer`. Defaults to the `LLMS_INK_KEY` environment variable
26
+ * where there is one. Recommended: proxies on shared hosting IPs otherwise share the anonymous limits.
27
+ */
28
+ key?: string;
29
+ /**
30
+ * Also answer `<path>.md`, and page requests whose `Accept` prefers `text/markdown` over `text/html`, with the
31
+ * page as Markdown (`https://llms.ink/full/<page>`). Default `false`.
32
+ */
33
+ markdown?: boolean;
34
+ /** Defaults to the `LLMS_INK_API` environment variable, else https://llms.ink. */
35
+ baseUrl?: string;
36
+ }
37
+ /** A fetch-API handler: a `Response` for the requests it serves, `undefined` for everything else. */
38
+ export type LlmsInkHandler = (request: Request) => Promise<Response | undefined>;
39
+ /**
40
+ * Answers `GET`/`HEAD` `/llms.txt` and `/llms-full.txt` with llms.ink's generated files for `site`
41
+ * (`native=0`, so a site whose /llms.txt is this handler can't loop), and, with `markdown: true`, Markdown
42
+ * versions of pages. Responses keep llms.ink's `Cache-Control`; each one is kept in memory for its `max-age`
43
+ * and served as a last good copy (with `Warning: 110`) when llms.ink fails. Returns `undefined` for every
44
+ * other request, and for llms.ink's own fetcher.
45
+ */
46
+ export declare function llmsInkHandler(options: LlmsInkHandlerOptions): LlmsInkHandler;
47
+ /** Node's `IncomingMessage` (Express, Connect, plain `node:http`), as far as the adapter reads it. */
48
+ export interface NodeRequest {
49
+ method?: string;
50
+ url?: string;
51
+ /** Express: the URL before mounting stripped a prefix. */
52
+ originalUrl?: string;
53
+ headers: Record<string, string | string[] | undefined>;
54
+ }
55
+ /** Node's `ServerResponse`, as far as the adapter writes it. */
56
+ export interface NodeResponse {
57
+ statusCode: number;
58
+ setHeader(name: string, value: string): unknown;
59
+ end(chunk: Uint8Array): unknown;
60
+ }
61
+ /** Express/Connect middleware: `next()` when the request isn't one {@link llmsInkHandler} serves. */
62
+ export type NodeMiddleware = (req: NodeRequest, res: NodeResponse, next: (err?: unknown) => void) => void;
63
+ /** {@link llmsInkHandler} as Express/Connect middleware: `app.use(llmsInkExpress({ site }))`. */
64
+ export declare function llmsInkExpress(options: LlmsInkHandlerOptions): NodeMiddleware;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Serve llms.txt, llms-full.txt and (optionally) Markdown versions of pages from llms.ink, inside your own app.
3
+ * A fetch-API handler for Cloudflare Workers, Next.js middleware, Deno, Bun and Hono, plus an Express/Connect
4
+ * adapter.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { llmsInkHandler } from 'llms-ink/middleware';
9
+ *
10
+ * const llms = llmsInkHandler({ site: 'https://example.com', markdown: true });
11
+ * export default {
12
+ * async fetch(request: Request): Promise<Response> {
13
+ * return (await llms(request)) ?? fetch(request); // undefined: not ours, the app answers
14
+ * },
15
+ * };
16
+ * ```
17
+ *
18
+ * @module
19
+ */
20
+ import { env } from "./env.js";
21
+ import { DEFAULT_BASE_URL, VERSION } from "./index.js";
22
+ const FILES = { '/llms.txt': 'llms', '/llms-full.txt': 'full' };
23
+ /** llms.ink's own fetcher (`compatible; llms.ink/0.1`): answering it from llms.ink would loop. */
24
+ const LLMS_INK_FETCHER = /\bllms\.ink\/\d/;
25
+ /** Response headers passed through from llms.ink. */
26
+ const PASS = ['content-type', 'cache-control', 'x-llms-kind', 'x-llms-source', 'x-llms-tokens'];
27
+ /** Pages kept in memory as last good copies; the oldest is dropped first. */
28
+ const MAX_ENTRIES = 200;
29
+ /** How long downstream caches may keep a stale copy served while llms.ink fails. */
30
+ const STALE_CACHE_CONTROL = 'public, max-age=60';
31
+ /**
32
+ * Answers `GET`/`HEAD` `/llms.txt` and `/llms-full.txt` with llms.ink's generated files for `site`
33
+ * (`native=0`, so a site whose /llms.txt is this handler can't loop), and, with `markdown: true`, Markdown
34
+ * versions of pages. Responses keep llms.ink's `Cache-Control`; each one is kept in memory for its `max-age`
35
+ * and served as a last good copy (with `Warning: 110`) when llms.ink fails. Returns `undefined` for every
36
+ * other request, and for llms.ink's own fetcher.
37
+ */
38
+ export function llmsInkHandler(options) {
39
+ const base = (options.baseUrl ?? env('LLMS_INK_API') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
40
+ const key = (options.key ?? env('LLMS_INK_KEY'))?.trim();
41
+ const site = new URL(/^https?:\/\//i.test(options.site) ? options.site : `https://${options.site}`);
42
+ const headers = { accept: 'text/plain', 'user-agent': `llms-ink-js/${VERSION}` };
43
+ if (key)
44
+ headers.authorization = `Bearer ${key}`;
45
+ const cache = new Map();
46
+ const pending = new Map();
47
+ /** Fetches `upstream`; on failure the last good copy, else llms.ink's error. */
48
+ async function refresh(upstream) {
49
+ const last = cache.get(upstream);
50
+ let res;
51
+ try {
52
+ res = await fetch(upstream, { headers });
53
+ }
54
+ catch (err) {
55
+ return last ? stale(last) : failure(502, 'upstream_error', `Couldn't reach llms.ink: ${err instanceof Error ? err.message : err}`);
56
+ }
57
+ // An older llms.ink without `format=text` answers JSON; never serve that as the file.
58
+ const isText = res.headers.get('content-type')?.startsWith('text/');
59
+ if (!res.ok || !isText) {
60
+ if (last) {
61
+ await res.body?.cancel();
62
+ return stale(last);
63
+ }
64
+ if (res.ok)
65
+ return failure(502, 'upstream_error', `llms.ink answered ${res.headers.get('content-type')}, not text.`);
66
+ return new Response(res.body, { status: res.status, headers: pick(res.headers, [...PASS, 'x-error-code', 'retry-after']) });
67
+ }
68
+ const maxAge = Number(/(?:^|,)\s*max-age=(\d+)/i.exec(res.headers.get('cache-control') ?? '')?.[1] ?? 0);
69
+ const entry = { body: await res.text(), headers: pick(res.headers, PASS), at: Date.now(), maxAge };
70
+ cache.delete(upstream);
71
+ cache.set(upstream, entry);
72
+ if (cache.size > MAX_ENTRIES)
73
+ cache.delete(cache.keys().next().value);
74
+ return fresh(entry);
75
+ }
76
+ async function serve(upstream) {
77
+ const hit = cache.get(upstream);
78
+ if (hit && Date.now() - hit.at < hit.maxAge * 1000)
79
+ return fresh(hit);
80
+ let loading = pending.get(upstream);
81
+ if (!loading) {
82
+ loading = refresh(upstream).finally(() => pending.delete(upstream));
83
+ pending.set(upstream, loading);
84
+ }
85
+ // Concurrent requests share one fetch; each gets its own copy of the body.
86
+ return (await loading).clone();
87
+ }
88
+ return async (request) => {
89
+ if (request.method !== 'GET' && request.method !== 'HEAD')
90
+ return undefined;
91
+ if (LLMS_INK_FETCHER.test(request.headers.get('user-agent') ?? ''))
92
+ return undefined;
93
+ const { pathname } = new URL(request.url);
94
+ const mode = FILES[pathname];
95
+ let response;
96
+ if (mode) {
97
+ const query = new URLSearchParams({ url: site.href, mode, native: '0', format: 'text' });
98
+ response = await serve(`${base}/api/v0/llms?${query}`);
99
+ }
100
+ else if (options.markdown && pathname.endsWith('.md')) {
101
+ const page = pathname.slice(0, -3).replace(/\/index$/, '/');
102
+ response = await serve(`${base}/full/${site.host}${page}`);
103
+ }
104
+ else if (options.markdown && isPage(pathname) && prefersMarkdown(request.headers.get('accept') ?? '')) {
105
+ response = await serve(`${base}/full/${site.host}${pathname}`);
106
+ response.headers.append('vary', 'Accept');
107
+ }
108
+ else {
109
+ return undefined;
110
+ }
111
+ return request.method === 'HEAD' ? new Response(null, response) : response;
112
+ };
113
+ }
114
+ /** {@link llmsInkHandler} as Express/Connect middleware: `app.use(llmsInkExpress({ site }))`. */
115
+ export function llmsInkExpress(options) {
116
+ const handle = llmsInkHandler(options);
117
+ return (req, res, next) => {
118
+ const headers = new Headers();
119
+ for (const name of ['accept', 'user-agent']) {
120
+ const value = req.headers[name];
121
+ if (typeof value === 'string')
122
+ headers.set(name, value);
123
+ }
124
+ const request = new Request(new URL(req.originalUrl ?? req.url ?? '/', 'http://localhost'), { method: req.method, headers });
125
+ handle(request)
126
+ .then(async (response) => {
127
+ if (!response)
128
+ return next();
129
+ res.statusCode = response.status;
130
+ response.headers.forEach((value, name) => res.setHeader(name, value));
131
+ res.end(new Uint8Array(await response.arrayBuffer()));
132
+ })
133
+ .catch(next);
134
+ };
135
+ }
136
+ function pick(from, names) {
137
+ const to = new Headers();
138
+ for (const name of names) {
139
+ const value = from.get(name);
140
+ if (value !== null)
141
+ to.set(name, value);
142
+ }
143
+ return to;
144
+ }
145
+ function fresh(entry) {
146
+ const headers = new Headers(entry.headers);
147
+ headers.set('age', String(Math.floor((Date.now() - entry.at) / 1000)));
148
+ return new Response(entry.body, { headers });
149
+ }
150
+ function stale(entry) {
151
+ const response = fresh(entry);
152
+ response.headers.set('cache-control', STALE_CACHE_CONTROL);
153
+ response.headers.set('warning', '110 - "Response is Stale"');
154
+ return response;
155
+ }
156
+ function failure(status, code, detail) {
157
+ return new Response(`${detail}\n`, { status, headers: { 'content-type': 'text/plain; charset=utf-8', 'x-error-code': code } });
158
+ }
159
+ /** A page path: no file extension, or `.html`/`.htm`. */
160
+ function isPage(pathname) {
161
+ const last = pathname.slice(pathname.lastIndexOf('/') + 1);
162
+ return !last.includes('.') || /\.html?$/i.test(last);
163
+ }
164
+ /**
165
+ * Whether `Accept` names `text/markdown` with a quality at least that of `text/html` (or, when `text/html`
166
+ * isn't listed, `text/*`, then `*\/*`). Browsers never list `text/markdown`, so they get the app.
167
+ */
168
+ function prefersMarkdown(accept) {
169
+ let markdown = 0;
170
+ const html = {};
171
+ for (const part of accept.toLowerCase().split(',')) {
172
+ const [type = '', ...params] = part.split(';').map((s) => s.trim());
173
+ const q = params.find((p) => p.startsWith('q='));
174
+ const quality = q === undefined ? 1 : Number(q.slice(2));
175
+ if (!Number.isFinite(quality))
176
+ continue;
177
+ if (type === 'text/markdown' || type === 'text/x-markdown')
178
+ markdown = Math.max(markdown, quality);
179
+ else if (type === 'text/html' || type === 'text/*' || type === '*/*')
180
+ html[type] = Math.max(html[type] ?? 0, quality);
181
+ }
182
+ return markdown > 0 && markdown >= (html['text/html'] ?? html['text/*'] ?? html['*/*'] ?? 0);
183
+ }
package/dist/vite.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Vite plugin: writes llms.txt (and llms-full.txt) from llms.ink into the build output.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * // vite.config.ts
7
+ * import { defineConfig } from 'vite';
8
+ * import { llmsInk } from 'llms-ink/vite';
9
+ *
10
+ * export default defineConfig({ plugins: [llmsInk({ site: 'https://example.com', full: true })] });
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import type { Plugin } from 'vite';
16
+ import { type LlmsFilesOptions } from './files.ts';
17
+ export type { LlmsFilesOptions };
18
+ /**
19
+ * After `vite build` (not the dev server, not SSR builds), fetches llms.txt — and llms-full.txt with
20
+ * `full: true` — for `site` and writes them into `build.outDir`. llms.ink reads the live site, so the files
21
+ * describe the previous deploy. When llms.ink can't be reached it warns and keeps any existing file (e.g. one
22
+ * copied from `public/`); `strict: true` fails the build instead.
23
+ */
24
+ export declare function llmsInk(options: LlmsFilesOptions): Plugin;
25
+ export default llmsInk;
package/dist/vite.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Vite plugin: writes llms.txt (and llms-full.txt) from llms.ink into the build output.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * // vite.config.ts
7
+ * import { defineConfig } from 'vite';
8
+ * import { llmsInk } from 'llms-ink/vite';
9
+ *
10
+ * export default defineConfig({ plugins: [llmsInk({ site: 'https://example.com', full: true })] });
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import { resolve } from 'node:path';
16
+ import { llmsFilesWriter } from "./files.js";
17
+ /**
18
+ * After `vite build` (not the dev server, not SSR builds), fetches llms.txt — and llms-full.txt with
19
+ * `full: true` — for `site` and writes them into `build.outDir`. llms.ink reads the live site, so the files
20
+ * describe the previous deploy. When llms.ink can't be reached it warns and keeps any existing file (e.g. one
21
+ * copied from `public/`); `strict: true` fails the build instead.
22
+ */
23
+ export function llmsInk(options) {
24
+ const write = llmsFilesWriter(options);
25
+ let config;
26
+ return {
27
+ name: 'llms-ink',
28
+ apply: 'build',
29
+ configResolved(resolved) {
30
+ config = resolved;
31
+ },
32
+ async closeBundle(error) {
33
+ if (error)
34
+ return;
35
+ // Vite 6+ runs the hook once per environment; only the browser build is served as static files.
36
+ const environment = this.environment;
37
+ if (environment ? environment.name !== 'client' : config.build.ssr)
38
+ return;
39
+ const { outDir } = environment ? environment.config.build : config.build;
40
+ await write(resolve(config.root, outDir), {
41
+ info: (message) => config.logger.info(`[llms-ink] ${message}`),
42
+ warn: (message) => config.logger.warn(`[llms-ink] ${message}`),
43
+ });
44
+ },
45
+ };
46
+ }
47
+ export default llmsInk;
package/package.json CHANGED
@@ -1,32 +1,57 @@
1
1
  {
2
2
  "name": "llms-ink",
3
- "version": "0.1.0",
4
- "description": "Turn any link — site, docs section, page, GitHub repo, PDF or video — into llms.txt and llms-full.txt. Typed client for llms.ink, no dependencies.",
3
+ "version": "0.3.0",
4
+ "description": "Turn any link — site, docs section, page, GitHub repo, PDF or video — into llms.txt and llms-full.txt. Typed client for llms.ink, plus a Vite plugin, an Astro integration and middleware that serve the files from your site. No dependencies.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
8
8
  "types": "./dist/index.d.ts",
9
9
  "default": "./dist/index.js"
10
+ },
11
+ "./vite": {
12
+ "types": "./dist/vite.d.ts",
13
+ "default": "./dist/vite.js"
14
+ },
15
+ "./astro": {
16
+ "types": "./dist/astro.d.ts",
17
+ "default": "./dist/astro.js"
18
+ },
19
+ "./middleware": {
20
+ "types": "./dist/middleware.d.ts",
21
+ "default": "./dist/middleware.js"
10
22
  }
11
23
  },
12
24
  "main": "./dist/index.js",
13
25
  "types": "./dist/index.d.ts",
14
26
  "files": ["dist"],
15
27
  "sideEffects": false,
28
+ "repository": { "type": "git", "url": "git+https://github.com/lukax/llms-ink-js.git" },
29
+ "bugs": "https://github.com/lukax/llms-ink-js/issues",
16
30
  "engines": { "node": ">=18" },
17
31
  "scripts": {
18
- "build": "tsc -p tsconfig.json",
32
+ "build": "rm -rf dist && tsc -p tsconfig.json",
19
33
  "prepublishOnly": "npm run build && npm test",
20
- "test": "npm run build && node --test test/client.test.mjs",
34
+ "test": "npm run build && node --test test/client.test.mjs test/plugins.test.mjs test/middleware.test.mjs",
21
35
  "test:live": "npm run build && node --test test/live.test.mjs",
22
- "test:bun": "npm run build && bun test ./test/client.test.mjs",
36
+ "test:bun": "npm run build && bun test ./test/client.test.mjs ./test/plugins.test.mjs ./test/middleware.test.mjs",
23
37
  "test:bun:live": "npm run build && bun test --timeout 300000 ./test/live.test.mjs"
24
38
  },
25
- "keywords": ["llms.txt", "llms-full.txt", "llm", "ai", "markdown", "docs", "context", "rag", "sdk", "llms-ink"],
39
+ "keywords": ["llms.txt", "llms-full.txt", "llm", "ai", "markdown", "docs", "context", "rag", "sdk", "llms-ink", "vite-plugin", "astro-integration", "middleware"],
26
40
  "homepage": "https://llms.ink/docs/",
27
41
  "author": "Lucas Espindola (https://lucasespindola.com)",
28
42
  "license": "MIT",
43
+ "peerDependencies": {
44
+ "astro": ">=4",
45
+ "vite": ">=5"
46
+ },
47
+ "peerDependenciesMeta": {
48
+ "astro": { "optional": true },
49
+ "vite": { "optional": true }
50
+ },
29
51
  "devDependencies": {
30
- "typescript": "^5.9.3"
52
+ "@types/node": "^22.20.5",
53
+ "astro": "^7.4.1",
54
+ "typescript": "^5.9.3",
55
+ "vite": "^8.3.8"
31
56
  }
32
57
  }