@estiva-app/interop 0.30.1 → 0.32.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.
@@ -1770,20 +1770,140 @@ depth = 0,
1770
1770
  * omitting it is exactly the old behaviour.
1771
1771
  */
1772
1772
  cache) {
1773
- let pointer;
1773
+ const pointer = addressPointerOf(naddr);
1774
+ if (!pointer)
1775
+ return null;
1776
+ const resolved = await resolveManifest(pointer, query, cache);
1777
+ if (!resolved)
1778
+ return null;
1779
+ const plan = planObject(naddr, pointer, resolved, depth);
1780
+ if (!plan)
1781
+ return null;
1782
+ const assembled = assembleObject(plan, await query(plan.filters));
1783
+ if (assembled.object.unreachable)
1784
+ return assembled.object;
1785
+ return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)));
1786
+ }
1787
+ /**
1788
+ * Many addressed objects in one round trip — PER-10.
1789
+ *
1790
+ * {@link resolveForeignObject} costs one request per object once the manifest
1791
+ * is cached, and a consumer holding a set re-reads the whole set on every
1792
+ * refresh: Peek's Screener asked once per followed file, every minute, and an
1793
+ * idle Desk spent 144 of 194 requests in five minutes on exactly that, against
1794
+ * a relay that meters 300 a minute per person across every tab. This reads the
1795
+ * same objects with the same filters, **all of them in one POST** — chunked at
1796
+ * `MAX_FILTERS_PER_QUERY` the way {@link conversationsOf} is, since each object
1797
+ * asks up to four filters — then one people lookup for the whole set.
1798
+ *
1799
+ * So a refresh is `ceil(filters / 128)` requests and a people lookup, where it
1800
+ * was one request per object and a lookup each: two for any set of up to 32
1801
+ * objects, whatever their number.
1802
+ *
1803
+ * ## Same filters, same objects
1804
+ *
1805
+ * Each object's filters are exactly the ones {@link resolveForeignObject}
1806
+ * sends, so each keeps its own `limit` — one busy file cannot starve another's
1807
+ * comments, which is why this is not one filter naming every address. The
1808
+ * answers come back pooled, and every object is picked back out of the pool on
1809
+ * its filters' own criteria, the rule `childrenFrom` already follows for the
1810
+ * children that share a request with their parent. The result is keyed by the
1811
+ * reference as given, and each object is what `resolveForeignObject` returns
1812
+ * for it.
1813
+ *
1814
+ * A reference that is not an address, or whose app has no manifest or no
1815
+ * projection for its kind, is `null` — as it is from the single form. An event
1816
+ * reference (`nevent`, a bare id) is not an address and is `null` here; that
1817
+ * is {@link resolveForeignEvent}'s.
1818
+ *
1819
+ * **A failed read rejects the whole call**, as the single form throws. There is
1820
+ * no partial answer to give: the objects arrive pooled, so a chunk that failed
1821
+ * could have held any of them.
1822
+ */
1823
+ export async function resolveForeignObjects(references, query,
1824
+ /** Defaults to asking the relay. The browser passes a cached lookup. */
1825
+ lookupPeople,
1826
+ /** See {@link ProjectionCache}. Omitting it still reads each app's manifest once per call. */
1827
+ cache) {
1828
+ const results = {};
1829
+ const asked = [];
1830
+ for (const reference of new Set(references)) {
1831
+ const pointer = addressPointerOf(reference);
1832
+ results[reference] = null;
1833
+ if (pointer)
1834
+ asked.push({ reference, pointer });
1835
+ }
1836
+ if (asked.length === 0)
1837
+ return results;
1838
+ // One manifest per app, never per object — the reason `conversationsOf`
1839
+ // groups the same way. A cache would share these too, but a caller without
1840
+ // one should not pay per object for what every object of an app shares.
1841
+ const byApp = new Map();
1842
+ for (const { pointer } of asked)
1843
+ byApp.set(manifestKeyOf(pointer), pointer);
1844
+ const manifests = new Map();
1845
+ await Promise.all([...byApp].map(async ([key, pointer]) => {
1846
+ const resolved = await resolveManifest(pointer, query, cache);
1847
+ if (resolved)
1848
+ manifests.set(key, resolved);
1849
+ }));
1850
+ const plans = asked.flatMap(({ reference, pointer }) => {
1851
+ const resolved = manifests.get(manifestKeyOf(pointer));
1852
+ const plan = resolved && planObject(reference, pointer, resolved, 0);
1853
+ return plan ? [{ reference, plan }] : [];
1854
+ });
1855
+ if (plans.length === 0)
1856
+ return results;
1857
+ // Two spellings of one object — its `naddr` and its plain address — are two
1858
+ // answers (each keeps its own `openUrl`) and one set of filters.
1859
+ const filters = [];
1860
+ const planned = new Set();
1861
+ for (const { plan } of plans) {
1862
+ if (planned.has(plan.address))
1863
+ continue;
1864
+ planned.add(plan.address);
1865
+ filters.push(...plan.filters);
1866
+ }
1867
+ const chunks = [];
1868
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
1869
+ chunks.push(filters.slice(start, start + MAX_FILTERS_PER_QUERY));
1870
+ }
1871
+ const events = (await Promise.all(chunks.map((chunk) => query(chunk)))).flat();
1872
+ const assembled = plans.map(({ reference, plan }) => ({ reference, built: assembleObject(plan, events) }));
1873
+ const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))];
1874
+ const reachable = assembled.some(({ built }) => !built.object.unreachable);
1875
+ const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {};
1876
+ for (const { reference, built } of assembled) {
1877
+ if (built.object.unreachable) {
1878
+ results[reference] = built.object;
1879
+ continue;
1880
+ }
1881
+ // Each object carries the people it names, as the single form's does —
1882
+ // not the whole set's, which would make an object's shape depend on what
1883
+ // it happened to be resolved beside.
1884
+ const own = {};
1885
+ for (const key of peopleOf(built))
1886
+ if (key in people)
1887
+ own[key] = people[key];
1888
+ results[reference] = withPeople(built, own);
1889
+ }
1890
+ return results;
1891
+ }
1892
+ /** An `naddr` or a `<kind>:<pubkey>:<d>`, or null for anything else. */
1893
+ function addressPointerOf(reference) {
1774
1894
  try {
1775
1895
  // Either form: a body carries `naddr1…`, an `a` tag carries the plain
1776
1896
  // address, and both name the same object (FEE-2).
1777
- pointer = referenceToPointer(naddr);
1897
+ return referenceToPointer(reference);
1778
1898
  }
1779
1899
  catch {
1780
1900
  return null;
1781
1901
  }
1902
+ }
1903
+ /** Null when the owning app has no projection for the kind. */
1904
+ function planObject(naddr, pointer, resolved, depth) {
1905
+ const { manifest } = resolved;
1782
1906
  const address = pointerToAddress(pointer);
1783
- const resolved = await resolveManifest(pointer, query, cache);
1784
- if (!resolved)
1785
- return null;
1786
- const { manifest, viaRecommendation } = resolved;
1787
1907
  // Substituted here rather than in the component: `<bech32>` is a NIP-89
1788
1908
  // detail, and the widget's job is to draw a link, not to know the spec.
1789
1909
  const openUrl = resolved.webTemplate?.replace('<bech32>', naddr.replace(/^nostr:/, ''));
@@ -1809,39 +1929,67 @@ cache) {
1809
1929
  one, and with the manifest memoised it is the whole cost of a tick.
1810
1930
  */
1811
1931
  const childFilter = childFilterFor({ projection, manifest, pointer, depth });
1812
- const events = await query([
1932
+ const filters = [
1813
1933
  { kinds: [pointer.kind], authors: [pointer.pubkey], '#d': [pointer.identifier], limit: 1 },
1814
1934
  // Only when the app actually declares a change kind — see `foldRuleOf`.
1815
1935
  ...(manifest.records ? [{ kinds: [manifest.records.changeKind], '#a': [address], limit: 500 }] : []),
1816
1936
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
1817
1937
  ...(childFilter ? [childFilter.filter] : []),
1818
- ]);
1819
- const root = events.find((e) => e.kind === pointer.kind && tagValue(e, 'd') === pointer.identifier);
1938
+ ];
1939
+ return { naddr, pointer, address, resolved, projection, records, commentKinds, childFilter, filters, openUrl };
1940
+ }
1941
+ /**
1942
+ * Build a planned object out of whatever the relay answered.
1943
+ *
1944
+ * **Every event is matched on the criteria of the filter that asked for it**,
1945
+ * because the answer may hold more than this object's own events: the root
1946
+ * shares its request with its children (SHI-13), and in
1947
+ * {@link resolveForeignObjects} with every other object in the set. So the root
1948
+ * is matched on its author as well as its kind and `d` — two apps' objects may
1949
+ * share both — and a fold runs only when the manifest declares change events,
1950
+ * since the substitute rule's `changeKind` is a placeholder that was never
1951
+ * asked for (`foldRuleOf`).
1952
+ *
1953
+ * Deduplicated by id first. The relay concatenates what each filter matched
1954
+ * rather than merging it (measured, see `conversationsOf`), so an event two
1955
+ * filters match — a comment naming two files in the set, a `kind:9` that is a
1956
+ * Topic's child and its comment — would otherwise be drawn twice.
1957
+ */
1958
+ function assembleObject(plan, answered) {
1959
+ const { naddr, pointer, address, resolved, projection, records, commentKinds, childFilter, openUrl } = plan;
1960
+ const { manifest, viaRecommendation } = resolved;
1961
+ const seen = new Set();
1962
+ const events = answered.filter((e) => !seen.has(e.id) && !!seen.add(e.id));
1963
+ const root = events.find((e) => e.kind === pointer.kind && e.pubkey === pointer.pubkey && tagValue(e, 'd') === pointer.identifier);
1820
1964
  if (!root) {
1821
1965
  // We know which app owns this and how it would be drawn; we just cannot see
1822
1966
  // the object. Say so rather than returning null and looking like a typo.
1823
1967
  return {
1824
- ref: address,
1825
- address,
1826
- naddr: naddr.replace(/^nostr:/, ''),
1827
- // Nothing was read, so there is no event to name. The reference is the
1828
- // address; that is all this case ever knows.
1829
- eventId: '',
1830
- kind: pointer.kind,
1831
- widget: projection.widget,
1832
- appName: manifest.name,
1833
- slots: {},
1834
- meta: [],
1835
- comments: [],
1836
- actions: [],
1837
- viaRecommendation,
1838
- // Offered even here. "You cannot see this object" is exactly when
1839
- // somebody wants to open it in the app that can.
1840
- openUrl,
1841
- unreachable: true,
1968
+ object: {
1969
+ ref: address,
1970
+ address,
1971
+ naddr: naddr.replace(/^nostr:/, ''),
1972
+ // Nothing was read, so there is no event to name. The reference is the
1973
+ // address; that is all this case ever knows.
1974
+ eventId: '',
1975
+ kind: pointer.kind,
1976
+ widget: projection.widget,
1977
+ appName: manifest.name,
1978
+ slots: {},
1979
+ meta: [],
1980
+ comments: [],
1981
+ actions: [],
1982
+ viaRecommendation,
1983
+ // Offered even here. "You cannot see this object" is exactly when
1984
+ // somebody wants to open it in the app that can.
1985
+ openUrl,
1986
+ unreachable: true,
1987
+ },
1842
1988
  };
1843
1989
  }
1844
- const folded = foldChanges(events.filter((e) => e.kind === records.changeKind && tagValue(e, records.targetTag) === address), records);
1990
+ const folded = foldChanges(manifest.records
1991
+ ? events.filter((e) => e.kind === records.changeKind && tagValue(e, records.targetTag) === address)
1992
+ : [], records);
1845
1993
  /*
1846
1994
  Matched on the comment filter's own criteria — the kind **and** the `a` tag.
1847
1995
 
@@ -1893,16 +2041,22 @@ cache) {
1893
2041
  webTemplate: resolved.webTemplate,
1894
2042
  viaRecommendation,
1895
2043
  });
1896
- // After the object, because who to ask about is not known until it is built.
1897
- // Folded into the same resolve rather than left to the renderer so the
1898
- // widget's skeleton covers the wait and a key is never briefly on screen.
1899
- // Children are included so one lookup covers the whole tree — a message list
1900
- // is mostly other people, and a second trip per child would show a column of
1901
- // keys while it ran.
1902
- const forPeople = [object, ...(children ?? [])];
1903
- const people = await (lookupPeople ?? peopleViaRelay(query))([
1904
- ...new Set(forPeople.flatMap(pubkeysIn)),
1905
- ]);
2044
+ return { object, ...(children ? { children } : {}) };
2045
+ }
2046
+ /**
2047
+ * Who an assembled object names — asked after the object, because who to ask
2048
+ * about is not known until it is built.
2049
+ *
2050
+ * Folded into the same resolve rather than left to the renderer so the
2051
+ * widget's skeleton covers the wait and a key is never briefly on screen.
2052
+ * Children are included so one lookup covers the whole tree — a message list
2053
+ * is mostly other people, and a second trip per child would show a column of
2054
+ * keys while it ran.
2055
+ */
2056
+ function peopleOf({ object, children }) {
2057
+ return [...new Set([object, ...(children ?? [])].flatMap(pubkeysIn))];
2058
+ }
2059
+ function withPeople({ object, children }, people) {
1906
2060
  return { ...object, people, ...(children ? { children: children.map((c) => ({ ...c, people })) } : {}) };
1907
2061
  }
1908
2062
  /**