@neurowire/ingest 0.2.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/dist/index.d.ts CHANGED
@@ -11,9 +11,29 @@ interface RawDocument {
11
11
  url: string;
12
12
  contentType: string;
13
13
  body: string;
14
+ etag?: string;
15
+ lastModified?: string;
16
+ /** True when the body was served from the cache via a 304 Not Modified. */
17
+ notModified?: boolean;
14
18
  }
19
+ /** A previously fetched response plus its validators, kept for conditional requests. */
20
+ interface CachedResponse {
21
+ url: string;
22
+ contentType: string;
23
+ body: string;
24
+ etag?: string;
25
+ lastModified?: string;
26
+ }
27
+ /** A store of cached responses, injected by the caller (the library keeps no global state). */
28
+ interface ConditionalCache {
29
+ get(url: string): CachedResponse | undefined;
30
+ set(url: string, value: CachedResponse): void;
31
+ }
32
+ /** A simple Map-backed ConditionalCache. */
33
+ declare function createMemoryCache(): ConditionalCache;
15
34
  interface FetchOptions {
16
35
  signal?: AbortSignal;
36
+ cache?: ConditionalCache;
17
37
  }
18
38
  /** Fetch a URL over HTTP(S), following redirects, returning the body and final URL. */
19
39
  declare function fetchDocument(url: string, options?: FetchOptions): Promise<RawDocument>;
@@ -92,6 +112,8 @@ interface FetchFeedOptions {
92
112
  signal?: AbortSignal;
93
113
  /** Max number of feed-link redirects to follow (default 3). */
94
114
  maxDepth?: number;
115
+ /** A conditional (ETag/Last-Modified) response cache, owned by the caller. */
116
+ cache?: ConditionalCache;
95
117
  }
96
118
  /** Fetch a URL (website, RSS, or Atom) and normalize it to a NeurowireFeed. */
97
119
  declare function fetchFeed(url: string, options?: FetchFeedOptions): Promise<NeurowireFeed>;
@@ -102,6 +124,8 @@ interface FetchMeshOptions {
102
124
  signal?: AbortSignal;
103
125
  /** Keep only the newest N merged entries. */
104
126
  limit?: number;
127
+ /** A conditional response cache shared by every mesh source. */
128
+ cache?: ConditionalCache;
105
129
  }
106
130
  /**
107
131
  * Fetch every source in a mesh (in parallel) and merge them into one feed.
@@ -124,10 +148,27 @@ declare function discoverFeedLink($: CheerioAPI, base: string): string | undefin
124
148
  */
125
149
  declare function autodetect($: CheerioAPI, ctx: ParseContext): NeurowireFeed | null;
126
150
 
151
+ /** A proposed tap plus a preview of what it extracts, so a user can author a tap without DOM-spelunking. */
152
+ interface TemplateProposal {
153
+ template: FeedTemplate;
154
+ matched: number;
155
+ sampleTitles: string[];
156
+ }
157
+ /**
158
+ * Inspect a feed-less HTML page and PROPOSE a FeedTemplate (CSS selectors) for it.
159
+ *
160
+ * Heuristic: find repeated item-like containers (sibling `article`/`li`/class-patterned
161
+ * `div`s that each hold a heading and an `<a href>`), pick the selector whose matched set
162
+ * is largest and consistent, then derive `title`/`link`/`date` selectors relative to the
163
+ * item. The candidate is validated by running `applyTemplate`: a proposal is returned only
164
+ * when it extracts at least one entry, otherwise `undefined`.
165
+ */
166
+ declare function proposeTemplate(html: string, url: string): TemplateProposal | undefined;
167
+
127
168
  /** Register a per-host template. Validated with zod; ignored if it has no `host`. */
128
169
  declare function registerTemplate(template: FeedTemplate): void;
129
170
  /** Look up a template for a URL's hostname. */
130
171
  declare function findTemplate(url: string): FeedTemplate | undefined;
131
172
  declare function listTemplates(): FeedTemplate[];
132
173
 
133
- export { type FeedDraft, type FeedKind, type FeedTemplate, FeedTemplateSchema, type FetchFeedOptions, type FetchMeshOptions, type FetchOptions, type ParseContext, type RawDocument, applyTemplate, autodetect, detectKind, discoverFeedLink, fetchDocument, fetchFeed, fetchMesh, finalizeFeed, findTemplate, ingestDocument, listTemplates, normDate, parseAtom, parseFeedString, parseJsonFeed, parseRdf, parseRss, registerTemplate, resolveUrl, stripHtml };
174
+ export { type CachedResponse, type ConditionalCache, type FeedDraft, type FeedKind, type FeedTemplate, FeedTemplateSchema, type FetchFeedOptions, type FetchMeshOptions, type FetchOptions, type ParseContext, type RawDocument, type TemplateProposal, applyTemplate, autodetect, createMemoryCache, detectKind, discoverFeedLink, fetchDocument, fetchFeed, fetchMesh, finalizeFeed, findTemplate, ingestDocument, listTemplates, normDate, parseAtom, parseFeedString, parseJsonFeed, parseRdf, parseRss, proposeTemplate, registerTemplate, resolveUrl, stripHtml };
package/dist/index.js CHANGED
@@ -16,6 +16,15 @@ function detectKind(contentType, body) {
16
16
  }
17
17
 
18
18
  // src/fetch.ts
19
+ function createMemoryCache() {
20
+ const store = /* @__PURE__ */ new Map();
21
+ return {
22
+ get: (url) => store.get(url),
23
+ set: (url, value) => {
24
+ store.set(url, value);
25
+ }
26
+ };
27
+ }
19
28
  var USER_AGENT = "Neurowire/0.1 (+https://github.com/neurowire/neurowire)";
20
29
  var ACCEPT = "application/atom+xml, application/rss+xml, application/feed+json, application/json;q=0.9, text/html;q=0.8, */*;q=0.5";
21
30
  async function fetchDocument(url, options = {}) {
@@ -28,17 +37,37 @@ async function fetchDocument(url, options = {}) {
28
37
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
29
38
  throw new Error(`Unsupported protocol: ${parsed.protocol}`);
30
39
  }
40
+ const headers = { "user-agent": USER_AGENT, accept: ACCEPT };
41
+ const cached = options.cache?.get(url);
42
+ if (cached?.etag) headers["if-none-match"] = cached.etag;
43
+ if (cached?.lastModified) headers["if-modified-since"] = cached.lastModified;
31
44
  const res = await fetch(url, {
32
45
  redirect: "follow",
33
46
  signal: options.signal,
34
- headers: { "user-agent": USER_AGENT, accept: ACCEPT }
47
+ headers
35
48
  });
49
+ if (res.status === 304 && cached) {
50
+ return {
51
+ url: cached.url,
52
+ contentType: cached.contentType,
53
+ body: cached.body,
54
+ etag: cached.etag,
55
+ lastModified: cached.lastModified,
56
+ notModified: true
57
+ };
58
+ }
36
59
  if (!res.ok) {
37
60
  throw new Error(`Upstream responded ${res.status} ${res.statusText} for ${url}`);
38
61
  }
39
62
  const contentType = res.headers.get("content-type") ?? "";
40
63
  const body = await res.text();
41
- return { url: res.url || url, contentType, body };
64
+ const etag = res.headers.get("etag") ?? void 0;
65
+ const lastModified = res.headers.get("last-modified") ?? void 0;
66
+ const finalUrl = res.url || url;
67
+ if (options.cache) {
68
+ options.cache.set(url, { url: finalUrl, contentType, body, etag, lastModified });
69
+ }
70
+ return { url: finalUrl, contentType, body, etag, lastModified };
42
71
  }
43
72
 
44
73
  // src/ingest.ts
@@ -538,7 +567,7 @@ async function fetchFeed(url, options = {}) {
538
567
  return ingest(url, options, 0);
539
568
  }
540
569
  async function ingest(url, options, depth) {
541
- const doc = await fetchDocument(url, { signal: options.signal });
570
+ const doc = await fetchDocument(url, { signal: options.signal, cache: options.cache });
542
571
  return ingestDocument(doc, options, depth);
543
572
  }
544
573
  async function ingestDocument(doc, options = {}, depth = 0) {
@@ -571,7 +600,7 @@ async function ingestDocument(doc, options = {}, depth = 0) {
571
600
  // src/mesh.ts
572
601
  import { mergeFeeds } from "@neurowire/core";
573
602
  async function fetchMesh(mesh, options = {}) {
574
- const fetchOptions = { signal: options.signal };
603
+ const fetchOptions = { signal: options.signal, cache: options.cache };
575
604
  const results = await Promise.allSettled(
576
605
  mesh.sources.map(
577
606
  async (source) => ({
@@ -589,10 +618,116 @@ async function fetchMesh(mesh, options = {}) {
589
618
  }
590
619
  return mergeFeeds(mesh.name, parts, { limit: options.limit });
591
620
  }
621
+
622
+ // src/html/propose.ts
623
+ import { load as load2 } from "cheerio";
624
+ var HEADING_SELECTOR = "h1, h2, h3, h4";
625
+ var TITLE_CANDIDATES = ["h2", "h3", "h1", "h4"];
626
+ function hostOf(url) {
627
+ try {
628
+ return new URL(url).hostname || void 0;
629
+ } catch {
630
+ return void 0;
631
+ }
632
+ }
633
+ function looksLikeItem($, el) {
634
+ const $el = $(el);
635
+ const hasLink = $el.is("a[href]") || $el.find("a[href]").length > 0;
636
+ const hasTitle = $el.find(HEADING_SELECTOR).length > 0 || $el.is("a[href]");
637
+ return hasLink && hasTitle;
638
+ }
639
+ function selectorFor($, el) {
640
+ const $el = $(el);
641
+ const tag = ($el.prop("tagName") ?? "div").toLowerCase();
642
+ const className = ($el.attr("class") ?? "").trim();
643
+ if (!className) return tag;
644
+ const first = className.split(/\s+/)[0];
645
+ return first ? `${tag}.${first}` : tag;
646
+ }
647
+ function candidateSelectors($) {
648
+ const counts = /* @__PURE__ */ new Map();
649
+ $("article, li, div, a[href]").each((_, el) => {
650
+ if (!looksLikeItem($, el)) return;
651
+ const selector = selectorFor($, el);
652
+ counts.set(selector, (counts.get(selector) ?? 0) + 1);
653
+ });
654
+ for (const base of ["article"]) {
655
+ const n = $(base).filter((_, el) => looksLikeItem($, el)).length;
656
+ if (n > 0) counts.set(base, Math.max(counts.get(base) ?? 0, n));
657
+ }
658
+ const anchorRooted = (selector) => selector === "a" || selector.startsWith("a.");
659
+ return [...counts.entries()].filter(([, n]) => n >= 2).sort((a, b) => b[1] - a[1] || Number(anchorRooted(a[0])) - Number(anchorRooted(b[0]))).map(([selector]) => selector);
660
+ }
661
+ function titleSelectorFor($, itemSelector) {
662
+ const $first = $(itemSelector).first();
663
+ if ($first.is("a[href]") && !$first.find(HEADING_SELECTOR).length) return "a";
664
+ for (const candidate of TITLE_CANDIDATES) {
665
+ if ($first.find(candidate).first().text().trim()) return candidate;
666
+ }
667
+ if ($first.find("a[href]").first().text().trim()) return "a";
668
+ return void 0;
669
+ }
670
+ function itemIsLink($, itemSelector) {
671
+ let total = 0;
672
+ let anchors = 0;
673
+ $(itemSelector).each((_, el) => {
674
+ total += 1;
675
+ if ($(el).is("a[href]")) anchors += 1;
676
+ });
677
+ return total > 0 && anchors === total;
678
+ }
679
+ function linkSelectorFor($, itemSelector, titleSelector) {
680
+ if (itemIsLink($, itemSelector)) return void 0;
681
+ const $first = $(itemSelector).first();
682
+ if ($first.find(`${titleSelector} a[href]`).length) return `${titleSelector} a`;
683
+ return "a";
684
+ }
685
+ function dateSelectorFor($, itemSelector) {
686
+ const $first = $(itemSelector).first();
687
+ if ($first.find("time").length) return "time";
688
+ if ($first.find("[datetime]").length) return "[datetime]";
689
+ return void 0;
690
+ }
691
+ function feedTitleOf($) {
692
+ const title = $("title").first().text().trim();
693
+ if (title) return title;
694
+ const h1 = $("h1").first().text().trim();
695
+ return h1 || void 0;
696
+ }
697
+ function proposeTemplate(html, url) {
698
+ const $ = load2(html);
699
+ const ctx = { sourceUrl: url };
700
+ let best;
701
+ for (const itemSelector of candidateSelectors($)) {
702
+ const titleSelector = titleSelectorFor($, itemSelector);
703
+ if (!titleSelector) continue;
704
+ const template = { item: itemSelector, title: titleSelector };
705
+ const host = hostOf(url);
706
+ if (host) template.host = host;
707
+ const feedTitle = feedTitleOf($);
708
+ if (feedTitle) template.feedTitle = feedTitle;
709
+ const link = linkSelectorFor($, itemSelector, titleSelector);
710
+ if (link) template.link = link;
711
+ const date = dateSelectorFor($, itemSelector);
712
+ if (date) template.date = date;
713
+ const feed = applyTemplate($, template, ctx);
714
+ const matched = feed.entries.length;
715
+ if (matched === 0) continue;
716
+ if (!best || matched > best.matched) {
717
+ best = {
718
+ template,
719
+ matched,
720
+ sampleTitles: feed.entries.slice(0, 5).map((e) => e.title)
721
+ };
722
+ }
723
+ }
724
+ return best;
725
+ }
592
726
  export {
593
727
  FeedTemplateSchema,
594
728
  applyTemplate,
595
729
  autodetect,
730
+ createMemoryCache,
596
731
  detectKind,
597
732
  discoverFeedLink,
598
733
  fetchDocument,
@@ -608,6 +743,7 @@ export {
608
743
  parseJsonFeed,
609
744
  parseRdf,
610
745
  parseRss,
746
+ proposeTemplate,
611
747
  registerTemplate,
612
748
  resolveUrl,
613
749
  stripHtml
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neurowire/ingest",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Fetch, detect, and parse RSS/Atom/RDF/JSON feeds and HTML pages into the Neurowire model.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -48,7 +48,7 @@
48
48
  "cheerio": "^1.0.0",
49
49
  "fast-xml-parser": "^4.5.1",
50
50
  "zod": "^3.24.1",
51
- "@neurowire/core": "0.3.0"
51
+ "@neurowire/core": "0.4.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@types/node": "^22.10.5",