@aeye/resources 0.3.9 → 0.8.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.
Files changed (224) hide show
  1. package/aeye-resources-converters.md +191 -0
  2. package/aeye-resources-graph.md +61 -7
  3. package/aeye-resources-parsers.md +42 -14
  4. package/aeye-resources-slicers.md +76 -8
  5. package/aeye-resources.md +24 -9
  6. package/dist/converters/data.d.ts +9 -0
  7. package/dist/converters/data.d.ts.map +1 -0
  8. package/dist/converters/data.js +78 -0
  9. package/dist/converters/data.js.map +1 -0
  10. package/dist/converters/folder.d.ts +13 -0
  11. package/dist/converters/folder.d.ts.map +1 -0
  12. package/dist/converters/folder.js +63 -0
  13. package/dist/converters/folder.js.map +1 -0
  14. package/dist/converters/index.d.ts +9 -0
  15. package/dist/converters/index.d.ts.map +1 -0
  16. package/dist/converters/index.js +22 -0
  17. package/dist/converters/index.js.map +1 -0
  18. package/dist/converters/markup.d.ts +6 -0
  19. package/dist/converters/markup.d.ts.map +1 -0
  20. package/dist/converters/markup.js +59 -0
  21. package/dist/converters/markup.js.map +1 -0
  22. package/dist/converters/pdf.d.ts +6 -0
  23. package/dist/converters/pdf.d.ts.map +1 -0
  24. package/dist/converters/pdf.js +70 -0
  25. package/dist/converters/pdf.js.map +1 -0
  26. package/dist/converters/tables.d.ts +12 -0
  27. package/dist/converters/tables.d.ts.map +1 -0
  28. package/dist/converters/tables.js +64 -0
  29. package/dist/converters/tables.js.map +1 -0
  30. package/dist/default.d.ts +9 -5
  31. package/dist/default.d.ts.map +1 -1
  32. package/dist/default.js +23 -8
  33. package/dist/default.js.map +1 -1
  34. package/dist/graph.d.ts +64 -6
  35. package/dist/graph.d.ts.map +1 -1
  36. package/dist/graph.js +127 -32
  37. package/dist/graph.js.map +1 -1
  38. package/dist/html/dom.d.ts +31 -0
  39. package/dist/html/dom.d.ts.map +1 -0
  40. package/dist/html/dom.js +194 -0
  41. package/dist/html/dom.js.map +1 -0
  42. package/dist/html/entities.d.ts +3 -0
  43. package/dist/html/entities.d.ts.map +1 -0
  44. package/dist/html/entities.js +33 -0
  45. package/dist/html/entities.js.map +1 -0
  46. package/dist/html/markdown.d.ts +30 -0
  47. package/dist/html/markdown.d.ts.map +1 -0
  48. package/dist/html/markdown.js +429 -0
  49. package/dist/html/markdown.js.map +1 -0
  50. package/dist/http/index.d.ts +5 -0
  51. package/dist/http/index.d.ts.map +1 -0
  52. package/dist/http/index.js +3 -0
  53. package/dist/http/index.js.map +1 -0
  54. package/dist/http/loader.d.ts +74 -0
  55. package/dist/http/loader.d.ts.map +1 -0
  56. package/dist/http/loader.js +248 -0
  57. package/dist/http/loader.js.map +1 -0
  58. package/dist/http/sniff.d.ts +38 -0
  59. package/dist/http/sniff.d.ts.map +1 -0
  60. package/dist/http/sniff.js +131 -0
  61. package/dist/http/sniff.js.map +1 -0
  62. package/dist/imports.d.ts +29 -0
  63. package/dist/imports.d.ts.map +1 -0
  64. package/dist/imports.js +53 -0
  65. package/dist/imports.js.map +1 -0
  66. package/dist/index.d.ts +28 -7
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +21 -6
  69. package/dist/index.js.map +1 -1
  70. package/dist/optional.d.ts +9 -0
  71. package/dist/optional.d.ts.map +1 -0
  72. package/dist/optional.js +17 -0
  73. package/dist/optional.js.map +1 -0
  74. package/dist/parsers/code.d.ts +1 -1
  75. package/dist/parsers/code.d.ts.map +1 -1
  76. package/dist/parsers/code.js +2 -2
  77. package/dist/parsers/code.js.map +1 -1
  78. package/dist/parsers/convert.d.ts +8 -0
  79. package/dist/parsers/convert.d.ts.map +1 -0
  80. package/dist/parsers/convert.js +40 -0
  81. package/dist/parsers/convert.js.map +1 -0
  82. package/dist/parsers/data.d.ts +8 -0
  83. package/dist/parsers/data.d.ts.map +1 -0
  84. package/dist/parsers/data.js +20 -0
  85. package/dist/parsers/data.js.map +1 -0
  86. package/dist/parsers/docx.d.ts +2 -2
  87. package/dist/parsers/docx.d.ts.map +1 -1
  88. package/dist/parsers/docx.js +9 -68
  89. package/dist/parsers/docx.js.map +1 -1
  90. package/dist/parsers/excel.d.ts +4 -1
  91. package/dist/parsers/excel.d.ts.map +1 -1
  92. package/dist/parsers/excel.js +17 -136
  93. package/dist/parsers/excel.js.map +1 -1
  94. package/dist/parsers/folder.d.ts +3 -0
  95. package/dist/parsers/folder.d.ts.map +1 -0
  96. package/dist/parsers/folder.js +21 -0
  97. package/dist/parsers/folder.js.map +1 -0
  98. package/dist/parsers/html.d.ts +5 -2
  99. package/dist/parsers/html.d.ts.map +1 -1
  100. package/dist/parsers/html.js +11 -33
  101. package/dist/parsers/html.js.map +1 -1
  102. package/dist/parsers/image.d.ts +1 -1
  103. package/dist/parsers/image.d.ts.map +1 -1
  104. package/dist/parsers/image.js +2 -2
  105. package/dist/parsers/image.js.map +1 -1
  106. package/dist/parsers/index.d.ts +13 -9
  107. package/dist/parsers/index.d.ts.map +1 -1
  108. package/dist/parsers/index.js +12 -9
  109. package/dist/parsers/index.js.map +1 -1
  110. package/dist/parsers/markdown.d.ts +1 -1
  111. package/dist/parsers/markdown.d.ts.map +1 -1
  112. package/dist/parsers/markdown.js +2 -2
  113. package/dist/parsers/markdown.js.map +1 -1
  114. package/dist/parsers/pdf.d.ts +2 -2
  115. package/dist/parsers/pdf.d.ts.map +1 -1
  116. package/dist/parsers/pdf.js +99 -119
  117. package/dist/parsers/pdf.js.map +1 -1
  118. package/dist/parsers/text.d.ts +1 -1
  119. package/dist/parsers/text.d.ts.map +1 -1
  120. package/dist/parsers/text.js +2 -2
  121. package/dist/parsers/text.js.map +1 -1
  122. package/dist/parsers/version.d.ts +42 -0
  123. package/dist/parsers/version.d.ts.map +1 -0
  124. package/dist/parsers/version.js +100 -0
  125. package/dist/parsers/version.js.map +1 -0
  126. package/dist/parsers/zip.d.ts +1 -1
  127. package/dist/parsers/zip.d.ts.map +1 -1
  128. package/dist/parsers/zip.js +12 -5
  129. package/dist/parsers/zip.js.map +1 -1
  130. package/dist/registry.d.ts +46 -3
  131. package/dist/registry.d.ts.map +1 -1
  132. package/dist/registry.js +97 -39
  133. package/dist/registry.js.map +1 -1
  134. package/dist/renderers/index.d.ts +2 -2
  135. package/dist/renderers/index.d.ts.map +1 -1
  136. package/dist/renderers/index.js +1 -1
  137. package/dist/renderers/index.js.map +1 -1
  138. package/dist/renderers/poppler.d.ts +1 -1
  139. package/dist/renderers/poppler.d.ts.map +1 -1
  140. package/dist/renderers/poppler.js +1 -1
  141. package/dist/renderers/poppler.js.map +1 -1
  142. package/dist/resolvers/file.d.ts +7 -1
  143. package/dist/resolvers/file.d.ts.map +1 -1
  144. package/dist/resolvers/file.js +26 -6
  145. package/dist/resolvers/file.js.map +1 -1
  146. package/dist/resolvers/folder.d.ts +18 -0
  147. package/dist/resolvers/folder.d.ts.map +1 -0
  148. package/dist/resolvers/folder.js +89 -0
  149. package/dist/resolvers/folder.js.map +1 -0
  150. package/dist/resolvers/index.d.ts +4 -3
  151. package/dist/resolvers/index.d.ts.map +1 -1
  152. package/dist/resolvers/index.js +4 -3
  153. package/dist/resolvers/index.js.map +1 -1
  154. package/dist/resolvers/url.d.ts +5 -1
  155. package/dist/resolvers/url.d.ts.map +1 -1
  156. package/dist/resolvers/url.js +13 -74
  157. package/dist/resolvers/url.js.map +1 -1
  158. package/dist/resolvers/zip.d.ts +1 -1
  159. package/dist/resolvers/zip.d.ts.map +1 -1
  160. package/dist/resolvers/zip.js +2 -2
  161. package/dist/resolvers/zip.js.map +1 -1
  162. package/dist/section-keys.d.ts +16 -0
  163. package/dist/section-keys.d.ts.map +1 -0
  164. package/dist/section-keys.js +24 -0
  165. package/dist/section-keys.js.map +1 -0
  166. package/dist/sections.d.ts +39 -0
  167. package/dist/sections.d.ts.map +1 -0
  168. package/dist/sections.js +118 -0
  169. package/dist/sections.js.map +1 -0
  170. package/dist/segmenters/default.d.ts +1 -1
  171. package/dist/segmenters/default.d.ts.map +1 -1
  172. package/dist/segmenters/default.js +1 -1
  173. package/dist/segmenters/default.js.map +1 -1
  174. package/dist/segmenters/index.d.ts +3 -3
  175. package/dist/segmenters/index.d.ts.map +1 -1
  176. package/dist/segmenters/index.js +2 -2
  177. package/dist/segmenters/index.js.map +1 -1
  178. package/dist/segmenters/langchain.d.ts +1 -1
  179. package/dist/segmenters/langchain.d.ts.map +1 -1
  180. package/dist/segmenters/langchain.js +1 -1
  181. package/dist/segmenters/langchain.js.map +1 -1
  182. package/dist/slicers/code.d.ts +30 -1
  183. package/dist/slicers/code.d.ts.map +1 -1
  184. package/dist/slicers/code.js +118 -32
  185. package/dist/slicers/code.js.map +1 -1
  186. package/dist/slicers/index.d.ts +3 -3
  187. package/dist/slicers/index.d.ts.map +1 -1
  188. package/dist/slicers/index.js +3 -3
  189. package/dist/slicers/index.js.map +1 -1
  190. package/dist/slicers/markdown.d.ts +15 -1
  191. package/dist/slicers/markdown.d.ts.map +1 -1
  192. package/dist/slicers/markdown.js +56 -27
  193. package/dist/slicers/markdown.js.map +1 -1
  194. package/dist/slicers/text.d.ts +1 -1
  195. package/dist/slicers/text.d.ts.map +1 -1
  196. package/dist/slicers/text.js +6 -4
  197. package/dist/slicers/text.js.map +1 -1
  198. package/dist/stack.d.ts +41 -0
  199. package/dist/stack.d.ts.map +1 -0
  200. package/dist/stack.js +56 -0
  201. package/dist/stack.js.map +1 -0
  202. package/dist/summaries.d.ts +11 -0
  203. package/dist/summaries.d.ts.map +1 -0
  204. package/dist/summaries.js +131 -0
  205. package/dist/summaries.js.map +1 -0
  206. package/dist/tables.d.ts +21 -0
  207. package/dist/tables.d.ts.map +1 -0
  208. package/dist/tables.js +113 -0
  209. package/dist/tables.js.map +1 -0
  210. package/dist/types.d.ts +140 -17
  211. package/dist/types.d.ts.map +1 -1
  212. package/dist/utils.d.ts +64 -3
  213. package/dist/utils.d.ts.map +1 -1
  214. package/dist/utils.js +156 -160
  215. package/dist/utils.js.map +1 -1
  216. package/dist/versions.d.ts +207 -0
  217. package/dist/versions.d.ts.map +1 -0
  218. package/dist/versions.js +217 -0
  219. package/dist/versions.js.map +1 -0
  220. package/dist/zip-internal.d.ts +9 -4
  221. package/dist/zip-internal.d.ts.map +1 -1
  222. package/dist/zip-internal.js +45 -19
  223. package/dist/zip-internal.js.map +1 -1
  224. package/package.json +33 -3
@@ -0,0 +1,191 @@
1
+ # @aeye/resources — versions, converters, sections, fetching and folders
2
+
3
+ A resource has a **raw** form (the bytes as they are stored or served) and, for many formats, an
4
+ **LLM-ready version** made from it by a **converter**: clean markdown from html, tables from a
5
+ spreadsheet, text page by page from a pdf, a pretty form of json or yaml, a listing of a folder. Keep
6
+ both: show either, and cut sections and slices from the version.
7
+
8
+ ## Versions (`@aeye/resources/versions`, browser safe)
9
+
10
+ Every shape is a zod schema with its type derived from it, so stored or sent versions can be checked.
11
+ The module imports only zod.
12
+
13
+ ```ts
14
+ import { resourceVersionSchema, versionText, versionMimeType, type ResourceVersion } from "@aeye/resources/versions";
15
+
16
+ type ResourceVersion =
17
+ | { kind: "markdown"; text: string; ...base } // html, docx, folders
18
+ | { kind: "text"; text: string; ...base }
19
+ | { kind: "code"; language: string; text: string; ...base } // json, yaml (pretty)
20
+ | { kind: "pages"; pages: string[]; ...base } // pdf
21
+ | { kind: "table"; tables: Table[]; ...base }; // csv, tsv, workbooks
22
+ // base: { converter: string; from: string /* source type */; title?: string; metadata?: Record<string, unknown> }
23
+ ```
24
+
25
+ What can be worked out is a function, not a field:
26
+
27
+ | Function | Gives |
28
+ | --- | --- |
29
+ | `versionText(v)` | the text: `text`, pages joined by `PAGE_BREAK` (`\f`), or tables as markdown (`## name` + GFM table, blocks joined by a blank line) |
30
+ | `versionMimeType(v)` | `text/markdown`, `text/plain`, or the code language's (`application/json`, `application/yaml`) |
31
+ | `tableToMarkdown(t)` / `tableBlock(t)` | one table as a GFM table / with its heading |
32
+ | `columnKinds(t)` | per column: `empty`, `boolean`, `integer`, `number`, `date` or `text` |
33
+ | `tableRecords(t)` | rows as records keyed by header, cells typed by column kind (blank/repeat headers get `column 3`, `name 2`) |
34
+
35
+ `RESOURCE_VERSION_KINDS` lists the kinds; `ResourceVersionOf<"table">` picks one. `folderListingSchema`
36
+ and `tableSchema` are here too.
37
+
38
+ ## Converters
39
+
40
+ ```ts
41
+ interface ResourceConverter {
42
+ id: string;
43
+ supportedTypes: ResourceType[];
44
+ priority?: number; // higher tried first; ties → most recently registered
45
+ isSupported?(type, ctx): boolean | Promise<boolean>; // e.g. its optional dependency is installed
46
+ convert(source: ResourceSource, ctx: { registry, options: ParseOptions }): Promise<ResourceVersion | undefined>;
47
+ }
48
+
49
+ registry.registerConverter(myConverter, { priority: 10 });
50
+ registry.getConverters("html"); // the stack, first tried first
51
+ registry.hasConverter("html");
52
+ await registry.convertSource(source); // version, or undefined (no converter / all declined → raw is LLM-ready)
53
+ await registry.convert("https://x.dev/page", { renderer }); // resolve + convert; { source (input buffered), version }
54
+ ```
55
+
56
+ A converter that returns `undefined` declines and one that throws falls back to the next; if all
57
+ throw, the error (or an `AggregateError`) is thrown. One-shot inputs are buffered so each converter
58
+ gets the whole input. Per-type options from `configureType` apply.
59
+
60
+ Built in (`DEFAULT_CONVERTERS`, registered by `createDefaultResourceRegistry`):
61
+
62
+ | Converter | Types | Version |
63
+ | --- | --- | --- |
64
+ | `htmlConverter` | html | markdown of the main content; `title`, and `description`, `language`, `canonicalUrl` in metadata |
65
+ | `docxConverter` | docx | markdown, through mammoth's html (needs `mammoth`) |
66
+ | `delimitedConverter` | csv, tsv | tables; RFC 4180, the csv delimiter detected (`, ; tab \|`); no dependency |
67
+ | `workbookConverter` | excel | tables per sheet, formatted cells (needs `xlsx`) |
68
+ | `pdfConverter` | pdf | pages (needs `pdf-parse`); scanned pages are empty — use the render/transcribe parsers for those |
69
+ | `jsonConverter` | json | json indented two spaces; json lines each pretty printed. Declines when already pretty or not json |
70
+ | `yamlConverter` | yaml | even yaml (needs `js-yaml`). Declines when it has comments (they would be lost), is invalid or already even |
71
+ | `folderConverter` | folder | markdown listing: `# name`, `Folder: <path>`, `- entry (type, size)` |
72
+
73
+ ### Html to markdown
74
+
75
+ `htmlToCleanMarkdown(html, options)` → `{ markdown, title?, description?, language?, canonicalUrl? }`
76
+ (`htmlToMarkdown` gives the markdown alone). It parses html into a tree (`parseHtml`: void elements,
77
+ raw text, implied end tags; never throws), drops scripts, styles, forms, iframes, svg and hidden
78
+ elements (`hidden`, `aria-hidden`, inline `display:none`), and with `content: "main"` (default) keeps
79
+ the `<main>` (or `role=main`), else the one `<article>`, else the body without its chrome (`nav`,
80
+ `aside`, `header`/`footer` outside content, chrome landmarks, and class/id words like `menu`,
81
+ `sidebar`, `cookie`, `share`). A nearly empty main falls back to the body; a page that is all chrome
82
+ keeps it. Out comes GitHub markdown: headings, paragraphs, nested/numbered lists, tables (colspans,
83
+ captions; one-column layout tables become blocks), fenced code with its language, inline code,
84
+ quotes, definitions, emphasis, links and images made absolute against `baseUrl` (or `<base href>`).
85
+ Fragment, `javascript:` and `data:` links and 1px images are dropped; line starts that would read as
86
+ markdown are escaped. Options: `baseUrl`, `content`, `links`, `images`, `dropTags`. Through the
87
+ registry it is `options.html`, with `baseUrl` defaulting to the resource's URL.
88
+
89
+ ## Parsing works from the version
90
+
91
+ Version parsers (`createVersionParser({ id, supportedTypes, defaultSlicer, fallback, links? })`)
92
+ convert through the registry's stack for the type (else `fallback`) and cut parts from the version:
93
+ a page per part (`#page/<n>`), a sheet per part (`#sheet/<i>`), otherwise one part (`#part/0`). The
94
+ version is kept on `resource.version`. Registering another converter for a type (say a Readability
95
+ one for html) changes what is parsed, sliced and sectioned with no other change. When the stack
96
+ declines, the parser declines too and the next parser (e.g. `textParser`) takes the raw text.
97
+
98
+ ## Sections of a version
99
+
100
+ ```ts
101
+ registry.sectionVersion(version); // or sectionVersion(version) for the defaults alone
102
+ // → [{ key, path, title, start, end }] offsets into versionText(version), covering it in order
103
+ ```
104
+
105
+ | Version | Cut by | Keys |
106
+ | --- | --- | --- |
107
+ | markdown | headings (fences ignored) | heading path `Guide > Usage`, `(root)` before the first heading |
108
+ | pages | page (its page break included) | `Page 1`, `Page 2` |
109
+ | table | table | `Sheet > Sheet - Table 2`, or the table's name, or `Table 1` |
110
+ | code (json, yaml) | top-level key (text before the first joins it) | `name`, `list` |
111
+ | anything else | whole | `(root)` |
112
+
113
+ Keys come from structure (`sectionKeys`; repeats get ` ~2`), so they survive edits around them.
114
+ `registry.registerSectioner({ id, supports(version), sections(version) })` adds a sectioner; newer
115
+ ones are asked first, so one can override a default for the versions it supports.
116
+
117
+ ## Fetching URLs
118
+
119
+ The url resolver fetches with `fetchResource(url, registry, options)`, also usable on its own:
120
+
121
+ ```ts
122
+ const page = await fetchResource("https://site.dev/docs", registry, {
123
+ fetch, // FetchFn, default global fetch (inject to test or proxy)
124
+ headers, timeoutMs /* 30000 */, maxBytes /* 50 MiB */, signal,
125
+ renderer, // PageRenderer, optional
126
+ render: "auto", // "never" | "auto" | "always"
127
+ });
128
+ page.source; // { location: final URL, input: Uint8Array, type?, mimeType (always), size, modifiedAt?, metadata }
129
+ page.detectedBy; // "content" | "header" | "extension" | "text" | "default"
130
+ page.charset; page.renderedBy; page.renderError; page.requestedUrl; page.url; page.status;
131
+ ```
132
+
133
+ - **Type detection** (`detectType`): magic numbers first (pdf, png, jpeg, gif, webp, bmp, ico; zips
134
+ told apart as docx or workbook by their entry names), then a specific `Content-Type`, then the URL
135
+ path's extension, then how the text starts (html, svg, xml, json), else `text`, or no type for
136
+ binary bytes. Generic types (`application/octet-stream`, `text/plain`) are looked past, and so is
137
+ a `text/*` type with no rule of its own (`text/typescript` says only `text`, so `a.ts` is
138
+ `typescript` by its extension; with no extension it labels plain `text`).
139
+ - **Mime type**: `source.mimeType` is always set. A specific declared mime type is kept as it is
140
+ (`application/javascript`); else the detected type's from `DEFAULT_TYPE_MIME_TYPES` (`markdown` →
141
+ `text/markdown`, `docx` → the wordprocessingml type, an image's by its extension); else
142
+ `text/plain` for text and `application/octet-stream` for binary bytes (`effectiveMimeType`).
143
+ - **Text** is decoded by BOM, declared charset, or (html) `<meta charset>`, and stored as utf-8
144
+ (`metadata.charset` keeps the original).
145
+ - **Redirects** are followed; the source is located at the final URL (`metadata.requestedUrl` keeps the
146
+ asked one). Non-2xx, timeouts and bodies over `maxBytes` throw; aborts throw an `AbortError`.
147
+ - `statUrl` probes with HEAD for type, size and modified time (falls back to the URL itself).
148
+
149
+ ### Content sniffing helpers
150
+
151
+ The pieces `detectType` is made of are exported for code that fetches its own way:
152
+
153
+ ```ts
154
+ import {
155
+ detectType, parseContentType, isGenericMimeType, sniffMagic, sniffText, looksBinary, decodeText, isUtf8Charset,
156
+ effectiveMimeType, DEFAULT_TYPE_MIME_TYPES,
157
+ } from "@aeye/resources";
158
+
159
+ detectType(registry, url, bytes, parseContentType(header)); // { type?, mimeType, detectedBy, binary }
160
+ parseContentType("Text/HTML; charset=UTF-8"); // { mimeType: "text/html", charset: "utf-8" }; undefined for none
161
+ isGenericMimeType("application/octet-stream"); // true (also text/plain, binary/octet-stream, application/unknown, …)
162
+ sniffMagic(bytes); // { type: "pdf", mimeType: "application/pdf" } by the first bytes, or undefined
163
+ sniffText(text); // { type: "html" | "svg" | "xml" | "json", mimeType } by how the text starts, or undefined
164
+ looksBinary(bytes); // true for a NUL byte, or many control characters, in the first 1024 bytes
165
+ decodeText(bytes, charset?, html?); // { text, charset }: BOM, then the declared charset, then <meta charset> for html
166
+ isUtf8Charset("us-ascii"); // true for utf-8 or ascii (no transcoding needed)
167
+ effectiveMimeType("markdown", "text/plain", { location: "/a.md", binary: false }); // "text/markdown"
168
+ ```
169
+
170
+ ### Page renderers
171
+
172
+ ```ts
173
+ interface PageRenderer {
174
+ readonly id: string;
175
+ render(request: { url; html; headers?; signal? }): Promise<{ html: string; url?: string }>;
176
+ }
177
+ ```
178
+
179
+ The library ships none; plug in a headless browser. With `render: "auto"` only pages that look built
180
+ by scripts go through it (`looksScriptRendered`: an empty app root like `<div id="root"></div>`, a
181
+ `<noscript>` asking for JavaScript, or scripts with almost no visible text). The rendered html
182
+ replaces the fetched html (`metadata.renderedBy`). In `auto` a failed render keeps the fetched html
183
+ (`metadata.renderError`); in `always` it throws. Pass `renderer`/`render` with the call that fetches, e.g. `registry.load(url, { renderer })`.
184
+
185
+ ## Folders
186
+
187
+ `folderResolver` (in the default registry, ahead of the file resolver) resolves an existing folder to a
188
+ `folder` resource: raw form a json `FolderListing` (`listFolder` gives it directly), version a
189
+ markdown listing, links one per entry, so `buildResourceGraph(registry, dir)` walks the tree. Options
190
+ under `folder`: `includeHidden`, `ignore` (`DEFAULT_FOLDER_IGNORE`), `maxEntries`
191
+ (`DEFAULT_FOLDER_MAX_ENTRIES`). `FOLDER_TYPE` is `"folder"`, `FOLDER_MIME_TYPE` is `"inode/directory"`.
@@ -28,7 +28,16 @@ interface ResourceResolver {
28
28
  (`bundle.zip#entry/doc.md`) and links **relative to another entry** (`./other.md`, `../assets/x.png`,
29
29
  `/root.md`) within the same archive. Registered first so entry-relative links beat file/url.
30
30
  - **fileResolver** — absolute paths, `file://` URLs, and relative paths against a non-web,
31
- non-zip `baseLocation`. Sets `modifiedAt`/`size` from `fs.stat`.
31
+ non-zip `baseLocation`. Sets `modifiedAt`/`size` from `fs.stat`. When the base is a script
32
+ (`javascript`, `typescript`, `jsx`, `tsx`), links are imports: see
33
+ [Script imports](#script-imports).
34
+ - **folderResolver** — absolute paths, `file://` URLs and relative links (against a local base) that name an
35
+ existing **folder**. It resolves to a `folder` resource whose raw form is its listing (json,
36
+ `folderListingSchema`): entries folders-first, each with location, kind, detected type, size and
37
+ modified time. `options.folder`: `includeHidden` (default false), `ignore` (default `.git`,
38
+ `node_modules`), `maxEntries` (default 1000; the rest are counted, `truncated` set). A script's
39
+ relative import of a folder (`./lib`) is not taken: module resolution gives its index file. Registered
40
+ ahead of the file resolver.
32
41
  - **urlResolver** — http(s) URLs, plus relative/root-relative/protocol-relative links resolved
33
42
  against an http(s) `baseLocation` (via `new URL`). Sets `modifiedAt` (`Last-Modified`) and `size`
34
43
  (`Content-Length`); `stat` uses a `HEAD` request.
@@ -44,6 +53,33 @@ const stat = await registry.statLink("./child.md", { baseLocation: parent.locati
44
53
  // → { location, modifiedAt?, size?, mimeType?, type? } | undefined
45
54
  ```
46
55
 
56
+ ### Script imports
57
+
58
+ From a script base, the file resolver follows node and TypeScript module resolution:
59
+
60
+ - Only a relative specifier (`./a`, `../a`, `/a`, `.`, `..`) names a file. A bare one (`react`,
61
+ `node:fs`, `@scope/pkg`) names a package, so `canResolve` is `false` and the graph records the
62
+ edge as `unresolved`.
63
+ - A relative import resolves to the first of its candidates that is a file: the path as written,
64
+ the TypeScript source its extension stands for (`./a.js` → `a.ts`, `a.tsx`; `.jsx` → `.tsx`;
65
+ `.mjs` → `.mts`; `.cjs` → `.cts`), the path plus each of `IMPORT_EXTENSIONS`
66
+ (`.ts .tsx .d.ts .mts .cts .js .jsx .mjs .cjs .json`), then `<path>/index` plus each of them.
67
+ With no candidate on disk, `stat` returns `undefined` and `resolve` resolves nothing.
68
+
69
+ The same steps are exported for code that checks files its own way (a sandbox, a virtual file
70
+ system):
71
+
72
+ ```ts
73
+ import { diskIsFile, importCandidates, isRelativeSpecifier, isScriptType, resolveImportPath, SCRIPT_TYPES } from "@aeye/resources";
74
+
75
+ isScriptType("tsx"); // true — one of SCRIPT_TYPES
76
+ isRelativeSpecifier("./store"); // true; "react" → false
77
+ importCandidates("/src/store.js"); // ["/src/store.js", "/src/store.ts", "/src/store.tsx", "/src/store.js.ts", …]
78
+ await resolveImportPath("/src/lib"); // "/src/lib/index.ts" — the first candidate that is a file on disk
79
+ await resolveImportPath("/src/lib", isFile); // with your own IsFile: (path) => Promise<boolean>
80
+ await diskIsFile("/src/lib/index.ts"); // true — the default IsFile: a file on disk (false for folders and missing paths)
81
+ ```
82
+
47
83
  ## Locations: "know exactly how to get it"
48
84
 
49
85
  Every location the system emits is **canonical and self-contained** (absolute file path, `file://`,
@@ -84,7 +120,8 @@ import { buildResourceGraph } from "@aeye/resources";
84
120
 
85
121
  const graph = await buildResourceGraph(registry, "/docs/index.md", {
86
122
  maxDepth: 5,
87
- followExternal: false, // don't fetch http links
123
+ followExternal: true, // also fetch pages the docs link to (off by default)
124
+ concurrency: 8, // load up to 8 targets at once (default 4)
88
125
  });
89
126
 
90
127
  graph.roots; // ResourceLocation[]
@@ -99,6 +136,9 @@ interface ResourceGraph { roots: string[]; nodes: Map<string, ResourceGraphNode>
99
136
  interface ResourceGraphNode {
100
137
  id; location; type; depth;
101
138
  modifiedAt?; resource: ParsedResource;
139
+ fetch?: GraphNodeFetch; // web nodes: { requestedUrl, url (final, = location), status, rendered, renderedBy?, renderError? }
140
+ bytes?: Uint8Array; // the raw bytes parsed, with keepBytes: true
141
+ contentRef?: string; // the ref keepBytes(fn) returned after storing them
102
142
  slices?: ResourceSlice[]; // present if includeSlices
103
143
  reused: boolean; // true if served from cache (incremental)
104
144
  edges: ResourceGraphEdge[]; // outgoing links
@@ -110,7 +150,7 @@ interface ResourceGraphEdge {
110
150
  link: ResourceLink;
111
151
  targetLocation?: string; targetId?: string;
112
152
  loaded: boolean; // is the target a node in the graph?
113
- reason?: "external" | "resource-links-disabled" | "filtered"
153
+ reason?: "external" | "resource-links-disabled" | "filtered" | "cross-origin"
114
154
  | "unresolved" | "max-depth" | "max-resources" | "skipped" | "error";
115
155
  error?: string;
116
156
  }
@@ -121,16 +161,28 @@ interface ResourceGraphEdge {
121
161
  | Option | Default | Effect |
122
162
  | --- | --- | --- |
123
163
  | `maxDepth` | ∞ | max link/child distance from a root |
124
- | `maxResources` | ∞ | cap on nodes loaded (existing nodes never re-counted) |
164
+ | `maxResources` | `1000` (`DEFAULT_GRAPH_MAX_RESOURCES`) | cap on nodes loaded (existing nodes never re-counted); `Infinity` lifts it |
165
+ | `concurrency` | `4` (`DEFAULT_GRAPH_CONCURRENCY`) | link targets probed/loaded at once |
125
166
  | `followChildren` | `true` | traverse children (zip entries, rendered pages) as nodes |
126
- | `followExternal` | `true` | follow external (http) links |
127
- | `followResourceLinks` | `true` | follow internal/relative links |
167
+ | `followExternal` | `false` | follow external links: http links from local files, or links to another site |
168
+ | `followResourceLinks` | `true` | follow internal/relative links (includes same-site links on web pages) |
169
+ | `sameOrigin` | `true` | with `followExternal`, a link found on a web page is only followed to the same origin (else `cross-origin`); local files can still link out to any site |
170
+ | `keepBytes` | `false` | keep each loaded node's raw bytes: `true` → `node.bytes`; `async ({location, type, mimeType?, bytes}) => ref` stores them and puts the ref on `node.contentRef` (reused and child nodes carry none) |
128
171
  | `includeSlices` | `false` | also slice each resource → `node.slices` |
129
172
  | `shouldFollow(link, from)` | — | per-link filter |
130
173
  | `shouldLoad(target)` | — | incremental: return false to skip parsing (target = `{location, modifiedAt, link, depth}`) |
131
174
  | `getCached(location, modifiedAt?)` | — | supply a previously-parsed resource to reuse |
132
175
  | `onNode(node)` | — | called as each node is added |
133
176
 
177
+ The walk goes one depth level at a time, so `node.depth` is the true shortest distance from a root
178
+ even with concurrency. `node.edges` stay in link order, but `graph.nodes` insertion order can vary
179
+ between runs. Concurrent links to the same target share one load.
180
+
181
+ **Safe defaults**: starting from a web page, the graph only crawls that site (relative and absolute
182
+ same-origin links), stops at 1000 nodes, and never leaves the site unless you set `followExternal`
183
+ (plus `sameOrigin: false` to crawl freely). URL fetches time out after 30 s and stop at 50 MiB
184
+ (`timeoutMs` / `maxBytes` on the options).
185
+
134
186
  De-duplication uses `statLink` to get a target's canonical location (and `modifiedAt`) **before**
135
187
  loading, so a URL/file referenced many times is fetched once, and cross-zip-entry links connect to
136
188
  the existing entry nodes the zip parser already produced.
@@ -151,7 +203,9 @@ const graph = await buildResourceGraph(registry, roots, {
151
203
 
152
204
  ## Gotchas
153
205
 
154
- - URL-hosted zips are not supported (zip parser/resolver read archives from disk).
206
+ - Zips that are not local files (fetched from a URL, nested in another zip, passed in memory) are
207
+ parsed from their bytes and kept in an in-memory cache (8 archives, LRU) under their location, so
208
+ links between their entries resolve while they stay cached.
155
209
  - Relative links *between* zip entries resolve correctly; a link from a zip entry pointing **outside**
156
210
  the archive won't (it stays archive-relative) and surfaces as an `unresolved`/`error` edge.
157
211
  - `statLink` issues a `HEAD` for URLs; servers that reject HEAD still yield a location (for dedup) but
@@ -64,22 +64,34 @@ registry.registerParser(csvSummaryParser);
64
64
 
65
65
  ## Built-in parsers
66
66
 
67
+ Parsers for formats with a **converter** (html, docx, csv/tsv, workbooks, pdf, json, yaml, folders) are
68
+ *version parsers* (`createVersionParser`): they convert the source to its LLM-ready version through the
69
+ registry's converter stack and cut their parts from it, keeping it on `resource.version`. See
70
+ [aeye-resources-converters.md](./aeye-resources-converters.md).
71
+
67
72
  - **textParser** — `text, json, csv, tsv, yaml, xml, svg, toml, ini`. Decodes UTF-8 into one text
68
73
  part. Extracts bare URLs; for **markup types** (`markupTypes`, default `xml`/`svg`) also extracts
69
- `href`/`src` links.
70
- - **markdownParser** — `markdown`. Extracts markdown links + URLs. Default slicer `markdown`.
71
- - **htmlParser** — `html`. Converts HTML → markdown (`htmlToMarkdown`), extracts `href`/`src` + URLs.
72
- Honors `options.renderUrl(url, signal)` to fetch rendered HTML (e.g. via headless browser) when the
73
- source is an http(s) URL.
74
+ `href`/`src` links. The fallback for json and yaml that are already pretty.
75
+ - **markdownParser** — `markdown`. Extracts markdown links + URLs; an image (`![alt](src)`) is a link whose
76
+ `targetType` is `image`, titled by its alt text (`extractLinksFromMarkdown`). Default slicer `markdown`.
77
+ - **htmlParser** — `html`. One part from the clean markdown version (main content, absolute links);
78
+ links come from the raw html (every `href`/`src`, navigation included) so crawls see them; each link's
79
+ `metadata` names its `tag` (`a`, `img`, `link`, `base`, …) and its `rel` words, so a crawl can follow anchors only,
80
+ skip `nofollow` and resolve against `<base href>` (`extractLinksFromHtml`). Rendering
81
+ script-built pages happens when fetching (see `renderer` in the converters doc).
82
+ - **jsonParser / yamlParser** — json and yaml through their pretty forms; they decline (falling back to
83
+ textParser) when the file is already pretty, does not parse, or (yaml) has comments.
84
+ - **folderParser** — `folder` (from the folder resolver). A markdown listing; every entry is a link.
74
85
  - **codeParser** — all `CODE_TYPES` (ts, js, py, go, rust, …). Extracts import/require + URLs.
75
86
  Default slicer `code`.
76
87
  - **imageParser** — `image`. Stores image bytes as an image part; optionally adds text parts from
77
88
  `options.transcribeImage` and `options.describeImage`.
78
89
  - **pdfRenderParser / pdfParser** — see PDF section.
79
- - **excelPdfParser / excelParser** — Excel/CSV/TSV. Base parser uses `xlsx`, detects multiple table
80
- regions per sheet, renders markdown tables, and stores structured tables in
81
- `resource.metadata.structuredTables`.
82
- - **docxPdfParser / docxParser** — DOCX. Base parser uses `mammoth` → markdown.
90
+ - **excelPdfParser / excelParser / delimitedParser** — workbooks through `xlsx`; csv/tsv read in-house
91
+ (no dependency). Blank rows split a sheet into tables; the table version is on `resource.version`
92
+ (`tables`, typed with `columnKinds` / `tableRecords`), one part per sheet (`#sheet/<i>`).
93
+ - **pdfParser** — page text through `pdf-parse`, one part per page (`#page/<n>`, `pageNumber` set).
94
+ - **docxPdfParser / docxParser** — DOCX. Base parser: `mammoth` → html → clean markdown.
83
95
  - **zipParser** — `zip`. Lists entries and parses each entry **through the registry** so its links
84
96
  become part of the graph (see graph doc); entries that can't be parsed in-memory fall back to a raw
85
97
  representation. Children carry `modifiedAt` from the zip entry date.
@@ -94,6 +106,7 @@ interface PdfParseOptions {
94
106
  renderDpi?: number; // default 150
95
107
  transcribePages?: boolean; // transcribe rendered pages → markdown text parts
96
108
  extractImages?: boolean;
109
+ pageOutputDir?: string; // keep page images here (caller owns them); default: temp dir, deleted
97
110
  }
98
111
  ```
99
112
 
@@ -126,6 +139,13 @@ await isPopplerAvailable(); // boolean — binaries present?
126
139
  When rendering is enabled, `pdfRenderParser` produces page-image **children** and (if
127
140
  `transcribePages`) parent text parts; otherwise it declines and `pdfParser` extracts text.
128
141
 
142
+ - Page images render to a temporary directory that is deleted afterwards; their bytes are kept in
143
+ each page's image part (`part.data`). Set `pdf.pageOutputDir` to keep the files there instead
144
+ (parts then carry `metadata.filePath` and no `data`).
145
+ - PDFs (and docx/excel for `convertToPdf`) do not need to be local files: in-memory, URL and
146
+ zip-entry sources are written to a temporary file for the renderer/converter, and `pdfParser`
147
+ reads the source's bytes directly.
148
+
129
149
  ## Registry-driven type detection
130
150
 
131
151
  Detection maps live on the registry (seeded from defaults) and are extensible:
@@ -143,26 +163,34 @@ registry.inferType("/x/a.ipynb"); // "notebook"
143
163
  registry.inferType("/x/y", "application/x-ipynb+json"); // "notebook"
144
164
  ```
145
165
 
146
- - Mime patterns take precedence over extensions; newly registered patterns are checked first.
166
+ - A mime type that maps to a specific type takes precedence over the extension
167
+ (`inferType("notes.txt", "text/markdown")` is `markdown`). One that matches only the catch-all
168
+ `^text/` pattern (`GENERIC_TEXT_TYPE`, `"text"`: `text/typescript`, `text/plain`) yields to the
169
+ extension (`inferType("a.ts", "text/typescript")` is `typescript`) and is the answer only when the
170
+ extension names nothing. Newly registered patterns are checked first.
147
171
  - Extension matching scans suffixes longest-first, so **compound extensions** like `.tar.gz` and
148
172
  `.test.ts` resolve correctly. Dockerfiles are detected by name.
149
173
  - Each registry instance has its own maps (no global leakage).
150
174
 
151
175
  Standalone helpers (operate on the default maps): `inferTypeFromLocation`,
152
- `inferTypeFromMimeType`, `inferTypeFromExtension(loc, map)`, `inferTypeFromMimePatterns(mime, list)`.
176
+ `inferTypeFromMimeType`, `inferTypeFromExtension(loc, map)`, `inferTypeFromMimePatterns(mime, list)`,
177
+ and `inferTypeFromRules(loc, mime, patterns, map)` (the precedence above, on your own tables).
153
178
  Exposed default tables: `DEFAULT_EXTENSION_TYPES`, `DEFAULT_MIME_TYPE_PATTERNS`, `CODE_TYPES`,
154
- `DEFAULT_MARKUP_TYPES`, `DEFAULT_IMAGE_EXTENSION_MIME` (+ `imageMimeTypeFromLocation`).
179
+ `DEFAULT_MARKUP_TYPES`, `DEFAULT_IMAGE_EXTENSION_MIME` (+ `imageMimeTypeFromLocation`),
180
+ `DEFAULT_TYPE_MIME_TYPES` (type → mime, + `effectiveMimeType`), `GENERIC_TEXT_TYPE`.
155
181
 
156
182
  ## Parse options (selected `ParseOptions` fields)
157
183
 
158
184
  | Field | Effect |
159
185
  | --- | --- |
160
- | `signal` | abort |
186
+ | `signal` | abort; an aborted operation throws the signal's reason (an `AbortError`; see `isAbortError`) |
187
+ | `timeoutMs` | URL fetch timeout, headers + body (default 30000; 0 disables) |
188
+ | `maxBytes` | max bytes downloaded per URL (default 50 MiB; 0 disables) |
161
189
  | `code` | `CodeParserOptions` (declaration/import patterns, `maxImportPrefixes`) |
162
190
  | `pdf` | `PdfParseOptions` (see above) |
163
191
  | `renderPdfPages`, `convertToPdf` | PDF render / doc→pdf conversion functions |
164
192
  | `transcribeImage`, `describeImage` | vision callbacks for images & PDF pages |
165
- | `renderUrl` | render an http(s) URL to HTML for the html parser |
193
+ | `html` | `HtmlToMarkdownOptions`: `baseUrl` (defaults to the resource's URL), `content` (`main`/`body`), `links`, `images`, `dropTags` |
166
194
  | `markupTypes` | which types get `href`/`src` extraction (default xml/svg) |
167
195
 
168
196
  All of these can be set per type via `configureType` or passed per call.
@@ -31,20 +31,61 @@ interface ResourceSlicer {
31
31
  Universal fallback. Splits each text part on boundary strings into contiguous, non-overlapping
32
32
  segments. No structural context.
33
33
  - Default boundaries: `["\n\n", "\n", " "]`.
34
- - Per-slice links: part links present in the text + bare URLs in the segment.
34
+ - Per-slice links: the part's links that appear in the slice + bare URLs in the segment.
35
+ - `slice.sectionId` = the part location (one section per part).
35
36
 
36
37
  ### `markdown` — `supportedTypes: ["markdown", "html"]`
37
- Heading-aware. Detects `#`–`######` headings, builds a heading breadcrumb
38
- (`slice.context.headings`, e.g. `Intro > Details`), then segments each section.
38
+ Heading-aware. Detects `#`–`######` headings (ignoring `#` lines inside `` ``` `` / `~~~` code
39
+ fences), builds a heading breadcrumb (`slice.context.headings`, e.g. `Intro > Details`), then
40
+ segments each section. Text before the first heading is its own section with no headings, so the
41
+ slices always cover the whole text. `slice.sectionId` = `<part>#section/<key>`, where the key comes
42
+ from the heading path (see [Stable section keys](#stable-section-keys)).
43
+ `splitMarkdownSections(text)` is exported and returns `{ start, end, headings, key }` per section.
39
44
  - Default boundaries: `["\n\n", "\n", ". ", " "]` (sentence-aware).
40
45
  - Per-slice links: markdown `[](…)` links + bare URLs. Used for HTML too (HTML is parsed to markdown).
41
46
 
42
47
  ### `code` — `supportedTypes: [...CODE_TYPES]`
43
- Declaration-aware. Splits at top-level declarations and attaches import context.
44
- - `slice.context.declaration` = the block's first line; `slice.context.prefixes` = the first
45
- `maxImportPrefixes` import lines.
48
+ Declaration-aware. Splits at top-level (unindented) declarations and attaches import context.
49
+ - Text before the first declaration (license header, imports) is its own block, so the slices
50
+ always cover the whole file. Doc comments, decorators and attributes directly above a declaration
51
+ stay with it.
52
+ - Declaration patterns per language (`CODE_DECLARATION_PATTERNS`): JS/TS, python, ruby, go, rust,
53
+ lua, shell, sql, graphql; other languages use a generic pattern (class/struct/fn/func/def/…).
54
+ - `slice.context.declaration` = the declaration line (undefined for the preamble);
55
+ `slice.context.prefixes` = the first `maxImportPrefixes` import lines.
56
+ - `slice.sectionId` = `<part>#block/<key>`, where the key comes from the declared name (see
57
+ [Stable section keys](#stable-section-keys)). `splitCodeBlocks(text, type, codeOptions)` is
58
+ exported and returns `{ start, end, declaration?, name?, path, key }` per block.
59
+ - The declared name is the identifier after the declaration keyword (`function add`, `class Store`,
60
+ `func (s *Server) Serve`, `impl<T> Store<T>`, `declare module "x"`), or group 1 of the type's
61
+ `CODE_NAME_PATTERNS` entry (`shell`: `deploy()` / `function deploy`; `sql`: `create table users`).
62
+ `declarationName(line, pattern, type?)` is exported. A nameless declaration (`export default
63
+ function () {}`) is keyed by its declaration line.
46
64
  - Default boundaries: `["\n\n", "\n", " "]`.
47
- - Per-slice links: import/require specifiers + bare URLs.
65
+ - Per-slice links: the part's links that appear in the slice + import/require specifiers + bare URLs.
66
+
67
+ ## Stable section keys
68
+
69
+ A section's key comes from its place in the structure, never from its position, so it stays the
70
+ same when text is added or moved around it. That keeps `sectionId`s (and the section summaries
71
+ cached under them) valid across edits.
72
+
73
+ ```ts
74
+ import { sectionKeys, ROOT_SECTION_KEY, SECTION_PATH_SEPARATOR } from "@aeye/resources";
75
+ // or, with no node imports (safe in a browser): from "@aeye/resources/section-keys"
76
+
77
+ sectionKeys([[], ["Guide"], ["Guide", "Usage"], ["Guide"]]);
78
+ // → ["(root)", "Guide", "Guide > Usage", "Guide ~2"]
79
+ ```
80
+
81
+ - A key is the path joined with `SECTION_PATH_SEPARATOR` (`" > "`); an empty path (text before
82
+ the first heading or declaration) is `ROOT_SECTION_KEY` (`"(root)"`).
83
+ - A path seen before in the same document gets ` ~2`, ` ~3`, … so keys stay unique.
84
+ - The markdown slicer's path is the heading breadcrumb; the code slicer's is the declared name (else
85
+ the declaration line). Use `sectionKeys` for your own slicers so their keys follow the same rules.
86
+
87
+ Every slicer de-duplicates a slice's links by value, so the `Links:` line in `embedText` lists each
88
+ link once, and only links that are in that slice.
48
89
 
49
90
  ## Slice options (`SliceOptions`)
50
91
 
@@ -65,9 +106,14 @@ All apply to every slicer and can be set **per call** or **per type** via `confi
65
106
  | `includeLinks` | `true` | add `Links: …` line |
66
107
  | `embedSeparator` | `"\n\n"` | joins embed-text lines |
67
108
  | `buildEmbedText` | built-in | full override: `(EmbedTextContext) => string` |
68
- | `code.declarationPattern` | TS/JS regex | what starts a code block |
109
+ | `code.declarationPattern` | per language (`CODE_DECLARATION_PATTERNS`) | what starts a code block |
110
+ | `code.topLevelOnly` | `true` | only unindented lines can start a block |
69
111
  | `code.importPattern` | import/require regex | what counts as an import prefix |
70
112
  | `code.maxImportPrefixes` | `5` | how many import lines to attach |
113
+ | `summarize` | — | `(SummaryRequest) => Promise<string \| undefined>`; see [Summaries](#summaries) |
114
+ | `summaryScope` | `"resource"` | `"resource"`, `"section"` or `"both"` |
115
+ | `summaryConcurrency` | `4` | max concurrent `summarize` calls |
116
+ | `minSectionSummaryChars` | `0` | skip summarizing sections shorter than this |
71
117
  | `signal` | — | abort |
72
118
 
73
119
  `embedText` is assembled by the built-in `buildEmbedText`/`collectEmbedContext` from the include-flags
@@ -78,6 +124,28 @@ registry.configureType("markdown", { maxChars: 1200, minChars: 200, includePartK
78
124
  const { slices } = await registry.load("/docs/guide.md");
79
125
  ```
80
126
 
127
+ ## Summaries
128
+
129
+ Pass `summarize` to add model-written context to every slice. It is called for the whole resource
130
+ and/or for each section (markdown section, code block, or text part). The results land in
131
+ `slice.context.summary` / `slice.context.sectionSummary` and in `embedText` as `Summary: …` and
132
+ `Section summary: …` lines.
133
+
134
+ ```ts
135
+ registry.configureType("markdown", {
136
+ summaryScope: "both",
137
+ summarize: async ({ scope, text, headings, signal }) =>
138
+ myModel(`Summarize this ${scope}${headings ? ` (${headings.join(" > ")})` : ""} in one sentence:\n\n${text}`, signal),
139
+ });
140
+ ```
141
+
142
+ - `SummaryRequest` = `{ scope, resource, text, sectionId?, headings?, declaration?, signal? }`.
143
+ - Results are cached on `resource.metadata.summary` and `resource.metadata.sectionSummaries`
144
+ (keyed by `sectionId`), so slicing the same resource again, or one reused from a graph cache, does
145
+ not call `summarize` again. Clear those fields to force a refresh.
146
+ - With `"both"`, a section that is the whole resource is not summarized twice.
147
+ - Return `undefined` to skip a summary. Errors from `summarize` propagate.
148
+
81
149
  ## Pluggable segmenters
82
150
 
83
151
  The slicers call a `TextSegmenter` for the raw split step:
package/aeye-resources.md CHANGED
@@ -12,6 +12,8 @@ embedding, follow links between them, and incrementally rebuild when sources cha
12
12
  > - [aeye-resources-parsers.md](./aeye-resources-parsers.md) — parsers, parser stacking, per-type config, PDF rendering, type inference.
13
13
  > - [aeye-resources-slicers.md](./aeye-resources-slicers.md) — slicers, slice options, pluggable segmenters (LangChain).
14
14
  > - [aeye-resources-graph.md](./aeye-resources-graph.md) — resolvers, locations, `modifiedAt`, the resource graph.
15
+ > - [aeye-resources-converters.md](./aeye-resources-converters.md) — LLM-ready versions (converters), sectioning
16
+ > versions, fetching URLs (type detection, page renderers), folders.
15
17
 
16
18
  ## Install / import
17
19
 
@@ -26,7 +28,7 @@ import { createDefaultResourceRegistry, defaultResourceRegistry } from "@aeye/re
26
28
  ```
27
29
 
28
30
  Optional peer dependencies are loaded lazily and only needed for specific formats/features:
29
- `pdf-parse` (PDF text), `mammoth` (DOCX), `xlsx` (Excel/CSV), `jszip` (ZIP), `node-poppler`
31
+ `pdf-parse` (PDF text), `mammoth` (DOCX), `xlsx` (Excel; csv/tsv need nothing), `js-yaml` (yaml pretty form), `jszip` (ZIP), `node-poppler`
30
32
  (PDF page rendering), `@langchain/textsplitters` (overlap/token/language-aware chunking). If a
31
33
  dependency is missing, the relevant parser/feature simply declines or reports unsupported.
32
34
 
@@ -34,11 +36,15 @@ dependency is missing, the relevant parser/feature simply declines or reports un
34
36
 
35
37
  ```
36
38
  input (path | URL | ResourceSource)
37
- └─ resolve → ResourceSource (resolvers: zip, file, url)
38
- └─ parse → ParsedResource (parser stack per type → parts, links, children)
39
+ └─ resolve → ResourceSource (resolvers: zip, folder, file, url)
40
+ └─ convert → ResourceVersion (converter stack per type → markdown, tables, pages, pretty code)
41
+ └─ parse → ParsedResource (parser stack per type → parts cut from the version, links, children)
39
42
  └─ slice → ResourceSlice[] (slicer per type → chunks + embedText)
40
43
  ```
41
44
 
45
+ `convert()` resolves and converts only (the raw source plus its LLM-ready version, for storing both);
46
+ `sectionVersion()` cuts a version into sections keyed by structure.
47
+
42
48
  `load()` does all three; `parse()` and `slice()` are also available individually.
43
49
 
44
50
  ```ts
@@ -63,6 +69,7 @@ interface ParsedResource {
63
69
  id: string; // `${location}::${type}`
64
70
  location: string; // canonical, self-contained location
65
71
  type: string; // e.g. "markdown", "pdf", "typescript"
72
+ version?: ResourceVersion; // the LLM-ready version the parts were cut from (html, docx, sheets, pdf, …)
66
73
  name: string;
67
74
  mimeType?: string;
68
75
  modifiedAt?: number; // epoch ms — for staleness/incremental rebuilds
@@ -93,8 +100,10 @@ interface ResourceSlice {
93
100
  text: string; // the slice content
94
101
  embedText: string; // text augmented with context/links, ready to embed
95
102
  start: number; end: number; // offsets into the part text
96
- context?: { headings?; declaration?; summary?; prefixes? };
97
- links: ResourceLink[]; metadata?: Record<string, unknown>;
103
+ context?: { headings?; declaration?; summary?; sectionSummary?; prefixes? };
104
+ links: ResourceLink[]; // links that appear in this slice, each once
105
+ sectionId?: string; // markdown section / code block / text part the slice came from
106
+ metadata?: Record<string, unknown>;
98
107
  }
99
108
  ```
100
109
 
@@ -148,12 +157,14 @@ registry.configureType("markdown", { maxChars: 1200, minChars: 200 });
148
157
 
149
158
  `createDefaultResourceRegistry()` registers:
150
159
 
160
+ - **Converters** (`DEFAULT_CONVERTERS`): html → markdown, docx → markdown, csv/tsv → tables, workbooks →
161
+ tables, pdf → pages, json → pretty json, yaml → even yaml, folder → markdown listing.
151
162
  - **Parsers** (stacked where useful): `textParser` (text/json/csv/tsv/yaml/xml/svg/toml/ini),
152
163
  `markdownParser`, `htmlParser`, `codeParser` (all `CODE_TYPES`), `imageParser`,
153
- `pdfRenderParser`→`pdfParser`, `excelPdfParser`→`excelParser`, `docxPdfParser`→`docxParser`,
154
- `zipParser`.
164
+ `pdfRenderParser`→`pdfParser`, `excelPdfParser`→`excelParser`, `delimitedParser` (csv/tsv),
165
+ `docxPdfParser`→`docxParser`, `jsonParser`/`yamlParser`→`textParser`, `folderParser`, `zipParser`.
155
166
  - **Slicers**: `textSlicer` (`*`), `markdownSlicer` (markdown/html), `codeSlicer` (code types).
156
- - **Resolvers** (tried in order): `zipResolver`, `fileResolver`, `urlResolver`.
167
+ - **Resolvers** (tried in order): `zipResolver`, `folderResolver`, `fileResolver`, `urlResolver`.
157
168
 
158
169
  All are exported individually too, so you can compose a custom registry.
159
170
 
@@ -182,5 +193,9 @@ const graph = await buildResourceGraph(registry, "/docs/index.md");
182
193
  or `isTypeSupported` returns false, not a hard crash (except when a format has no fallback).
183
194
  - File locations are emitted **absolute** so they round-trip; a manually-supplied *relative*
184
195
  `location` is not self-contained (`locate()` rejects it).
185
- - Zips are read from disk (URL-hosted zips are not supported by the zip parser/resolver).
196
+ - Zips and PDFs can come from anywhere (disk, URL, memory, another zip). Non-local zips are cached
197
+ in memory (8, LRU) so their entry links resolve.
198
+ - `buildResourceGraph` is bounded by default: no external links, same-site web crawling, 1000
199
+ nodes max. Opt in with `followExternal`, `sameOrigin: false`, `maxResources: Infinity`.
200
+ - Aborts throw an `AbortError` (the signal's reason), not a plain `Error`.
186
201
  - `modifiedAt` is best-effort: filesystem mtime, HTTP `Last-Modified`, or zip entry date.
@@ -0,0 +1,9 @@
1
+ import type { ResourceConverter } from "../types.js";
2
+ /**
3
+ * Json indented two spaces. Json lines (one value per line, `.jsonl`) have each line pretty printed, separated by a
4
+ * blank line. Text that is neither is declined.
5
+ */
6
+ export declare const jsonConverter: ResourceConverter;
7
+ /** Yaml written out evenly: two-space indents, block style, documents separated by `---`. */
8
+ export declare const yamlConverter: ResourceConverter;
9
+ //# sourceMappingURL=data.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../src/converters/data.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAkB,MAAM,aAAa,CAAC;AA4BrE;;;GAGG;AACH,eAAO,MAAM,aAAa,EAAE,iBAa3B,CAAC;AAEF,6FAA6F;AAC7F,eAAO,MAAM,aAAa,EAAE,iBAsB3B,CAAC"}