@estiva-app/interop 0.36.0 → 0.37.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.
@@ -941,6 +941,18 @@ function webTemplate(event, entity) {
941
941
  * served by the plain noun.
942
942
  */
943
943
  export const KIND_BARE_FILE = 30840;
944
+ /**
945
+ * The field that archives a file, whatever its kind — FOL-46.
946
+ *
947
+ * **One concept for every file.** A Ship project, a Ship issue, a Peek topic, a
948
+ * bare file and a Folder are all archived the same way: a change setting
949
+ * `archived` to `'true'` on the file's address, and an empty value to restore
950
+ * it. That is the shape Ship has written for projects since SPEC §6.5, so
951
+ * nothing on the relay needs migrating. It is a change, never a deletion, so it
952
+ * is reversible, attributed, and open to anyone who may write in the Folder —
953
+ * not only the author.
954
+ */
955
+ export const ARCHIVED_FIELD = 'archived';
944
956
  /**
945
957
  * Where a `ResolvedManifest.address` would name the manifest event, this names
946
958
  * the section of the specification the manifest is built from. Not an address,
@@ -1048,6 +1060,22 @@ const BARE_FILE_MANIFEST = {
1048
1060
  emits: { kind: 1851, field: 'parent' },
1049
1061
  input: { type: 'string' },
1050
1062
  },
1063
+ /*
1064
+ `archive` is the one field every file may carry (FOL-46): `true` hides the
1065
+ file and everything under it from every list, an empty value brings it
1066
+ back. A change, so anyone in the team may, and the archiving change's
1067
+ `content` is the resolution summary a person gave (`ActionEventArgs.note`).
1068
+ */
1069
+ {
1070
+ id: 'archive',
1071
+ label: 'Archive',
1072
+ description: 'Take this file and everything under it out of every list once nobody needs to see it, or bring it ' +
1073
+ 'back: `true` archives, an empty value restores. Nothing is deleted, and a link still opens it.',
1074
+ effect: 'writes',
1075
+ appliesTo: [String(KIND_BARE_FILE)],
1076
+ emits: { kind: 1851, field: ARCHIVED_FIELD },
1077
+ input: { type: 'string', enum: ARCHIVED_FIELD },
1078
+ },
1051
1079
  {
1052
1080
  id: 'delete',
1053
1081
  label: 'Delete',
@@ -1058,6 +1086,13 @@ const BARE_FILE_MANIFEST = {
1058
1086
  emits: { kind: KIND_DELETION },
1059
1087
  },
1060
1088
  ],
1089
+ vocabularies: {
1090
+ // Ship's `ARCHIVED_STATES`, value for value: one field, one vocabulary.
1091
+ [ARCHIVED_FIELD]: [
1092
+ { value: '', label: 'Active', colour: 'neutral' },
1093
+ { value: 'true', label: 'Archived', colour: 'muted' },
1094
+ ],
1095
+ },
1061
1096
  };
1062
1097
  function bareFileManifest() {
1063
1098
  return { manifest: BARE_FILE_MANIFEST, address: BARE_FILE_MANIFEST_ADDRESS, viaRecommendation: false };
@@ -1414,6 +1449,83 @@ function foldChanges(changes, rule) {
1414
1449
  }
1415
1450
  return fields;
1416
1451
  }
1452
+ /**
1453
+ * How an `archived` change is read when the file's kind declares no rule of its
1454
+ * own — a Folder, whose `kind:39000` no app owns, and a bare file. SPEC §7.1's
1455
+ * `kind:1851` shape, the one every Estiva app writes.
1456
+ */
1457
+ const ARCHIVE_RULE = {
1458
+ changeKind: 1851,
1459
+ targetTag: 'a',
1460
+ fieldTag: 'field',
1461
+ valueTag: 'value',
1462
+ order: ['ts', 'created_at', 'id'],
1463
+ rule: 'last-write-wins-per-field',
1464
+ };
1465
+ /** The rule an `archived` change on this file is folded by: its app's, or SPEC's. */
1466
+ function archiveRuleOf(manifest) {
1467
+ return manifest?.records ?? ARCHIVE_RULE;
1468
+ }
1469
+ /**
1470
+ * The note Ship wrote on every archive before FOL-46, when the note was the
1471
+ * activity feed's wording rather than anything a person typed. Twelve are on
1472
+ * production (measured 2026-09-29), and none of them is a resolution.
1473
+ */
1474
+ const PLACEHOLDER_ARCHIVE_NOTE = 'archived';
1475
+ /**
1476
+ * Whether a file — or a Folder — is archived, itself or with an ancestor.
1477
+ *
1478
+ * Reads the {@link Archive} a resolver put on it. A resolver leaves archived
1479
+ * files out of a Folder's contents, so this matters where a file is reached
1480
+ * directly: a link, a mention, a page opened by address.
1481
+ */
1482
+ export function isArchived(file) {
1483
+ return !!file?.archived;
1484
+ }
1485
+ /**
1486
+ * The file's archive, if the last `archived` change archived it.
1487
+ *
1488
+ * `changes` may hold any events; only this rule's change kind, naming this
1489
+ * address, setting this field, is read. Last write wins, by the same order as
1490
+ * every other field.
1491
+ */
1492
+ function archiveOf(changes, address, rule) {
1493
+ let last;
1494
+ for (const change of changes) {
1495
+ // The target is the first target tag, as every other fold reads it: a
1496
+ // change archiving one file must not archive another it also mentions.
1497
+ if (change.kind !== rule.changeKind || tagValue(change, rule.targetTag) !== address)
1498
+ continue;
1499
+ if (tagValue(change, rule.fieldTag) !== ARCHIVED_FIELD || tagValue(change, rule.valueTag) === undefined)
1500
+ continue;
1501
+ if (!last || byOrder(last, change) < 0)
1502
+ last = change;
1503
+ }
1504
+ if (!last || tagValue(last, rule.valueTag) !== 'true')
1505
+ return undefined;
1506
+ const note = last.content.trim();
1507
+ return {
1508
+ by: last.pubkey,
1509
+ at: last.created_at,
1510
+ ...(note && note !== PLACEHOLDER_ARCHIVE_NOTE ? { resolution: last.content } : {}),
1511
+ };
1512
+ }
1513
+ /**
1514
+ * The first archived ancestor of `address`, walking `parentOf`, with its archive.
1515
+ *
1516
+ * Stops at a cycle rather than looping: `parentRef` is written by people, and
1517
+ * two files each moved under the other is a state the relay accepts.
1518
+ */
1519
+ function archivedAncestorOf(address, parentOf, archiveAt) {
1520
+ const seen = new Set([address]);
1521
+ for (let parent = parentOf(address); parent && !seen.has(parent); parent = parentOf(parent)) {
1522
+ seen.add(parent);
1523
+ const archive = archiveAt(parent);
1524
+ if (archive)
1525
+ return { ...archive, with: archive.with ?? parent };
1526
+ }
1527
+ return undefined;
1528
+ }
1417
1529
  function truncate(text, limit) {
1418
1530
  if (!limit || text.length <= limit)
1419
1531
  return text;
@@ -1839,6 +1951,7 @@ function buildObject(args) {
1839
1951
  ? { ...action, current: held[action.field] }
1840
1952
  : action),
1841
1953
  viaRecommendation: args.viaRecommendation,
1954
+ ...(args.archived ? { archived: args.archived } : {}),
1842
1955
  };
1843
1956
  }
1844
1957
  /**
@@ -1932,7 +2045,7 @@ depth = 0,
1932
2045
  * Optional memo for the NIP-89 discovery half. See {@link ProjectionCache} —
1933
2046
  * omitting it is exactly the old behaviour.
1934
2047
  */
1935
- cache) {
2048
+ cache, options = {}) {
1936
2049
  const pointer = addressPointerOf(naddr);
1937
2050
  if (!pointer)
1938
2051
  return null;
@@ -1945,6 +2058,8 @@ cache) {
1945
2058
  const assembled = assembleObject(plan, await query(plan.filters));
1946
2059
  if (assembled.object.unreachable)
1947
2060
  return assembled.object;
2061
+ if (options.archivedWith)
2062
+ await markArchivedParents([assembled.object], query);
1948
2063
  return withPeople(assembled, await (lookupPeople ?? peopleViaRelay(query))(peopleOf(assembled)));
1949
2064
  }
1950
2065
  /**
@@ -1987,7 +2102,7 @@ export async function resolveForeignObjects(references, query,
1987
2102
  /** Defaults to asking the relay. The browser passes a cached lookup. */
1988
2103
  lookupPeople,
1989
2104
  /** See {@link ProjectionCache}. Omitting it still reads each app's manifest once per call. */
1990
- cache) {
2105
+ cache, options = {}) {
1991
2106
  const results = {};
1992
2107
  const asked = [];
1993
2108
  for (const reference of new Set(references)) {
@@ -2033,6 +2148,8 @@ cache) {
2033
2148
  }
2034
2149
  const events = (await Promise.all(chunks.map((chunk) => query(chunk)))).flat();
2035
2150
  const assembled = plans.map(({ reference, plan }) => ({ reference, built: assembleObject(plan, events) }));
2151
+ if (options.archivedWith)
2152
+ await markArchivedParents(assembled.map(({ built }) => built.object), query);
2036
2153
  const wanted = [...new Set(assembled.flatMap(({ built }) => peopleOf(built)))];
2037
2154
  const reachable = assembled.some(({ built }) => !built.object.unreachable);
2038
2155
  const people = reachable ? await (lookupPeople ?? peopleViaRelay(query))(wanted) : {};
@@ -2052,6 +2169,59 @@ cache) {
2052
2169
  }
2053
2170
  return results;
2054
2171
  }
2172
+ /**
2173
+ * Mark each object that is hidden with an archived parent — FOL-46.
2174
+ *
2175
+ * An issue whose project is archived is archived with it, and its page says so
2176
+ * rather than drawing live work. The cascade is computed here and never written
2177
+ * to the issue, so unarchiving the project restores it exactly.
2178
+ *
2179
+ * **One read for the whole set, and only when some object has a parent**, so a
2180
+ * topic page or a project page pays nothing. One level: the parent's own
2181
+ * parent is not followed, because the page is about this file and its
2182
+ * container, and a deeper walk is a round trip per level. A Folder listing
2183
+ * walks the whole chain it holds ({@link resolveFolderContents}).
2184
+ *
2185
+ * The parent is folded by SPEC's rule, which every Estiva app writes: the
2186
+ * parent may belong to another app, whose manifest is not in hand.
2187
+ */
2188
+ async function markArchivedParents(objects, query) {
2189
+ const waiting = objects.filter((o) => !o.unreachable && !o.archived && o.parentRef && addressPointerOf(o.parentRef));
2190
+ if (waiting.length === 0)
2191
+ return;
2192
+ const parents = [...new Set(waiting.map((o) => o.parentRef))];
2193
+ const changes = await readArchiveChanges(parents, query);
2194
+ for (const object of waiting) {
2195
+ const archive = archiveOf(changes, object.parentRef, ARCHIVE_RULE);
2196
+ if (archive)
2197
+ object.archived = { ...archive, with: object.parentRef };
2198
+ }
2199
+ }
2200
+ /**
2201
+ * Addresses per filter when reading archive changes. A filter's `limit` caps
2202
+ * every change naming its addresses — titles, statuses, moves — not only the
2203
+ * archives, and a relay answers newest first, so a small group keeps the
2204
+ * archive change inside the page.
2205
+ */
2206
+ const ARCHIVE_READ_GROUP = 25;
2207
+ /** The filters asking for every SPEC-shaped change naming these addresses. */
2208
+ function archiveFilters(addresses) {
2209
+ const filters = [];
2210
+ for (let start = 0; start < addresses.length; start += ARCHIVE_READ_GROUP) {
2211
+ const group = addresses.slice(start, start + ARCHIVE_READ_GROUP);
2212
+ filters.push({ kinds: [ARCHIVE_RULE.changeKind], '#a': group, limit: RELAY_PAGE_CEILING });
2213
+ }
2214
+ return filters;
2215
+ }
2216
+ /** Every SPEC-shaped change naming these addresses, in as few requests as the relay allows. */
2217
+ async function readArchiveChanges(addresses, query) {
2218
+ const filters = archiveFilters(addresses);
2219
+ const events = [];
2220
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
2221
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
2222
+ }
2223
+ return events;
2224
+ }
2055
2225
  /** An `naddr` or a `<kind>:<pubkey>:<d>`, or null for anything else. */
2056
2226
  function addressPointerOf(reference) {
2057
2227
  try {
@@ -2096,6 +2266,9 @@ function planObject(naddr, pointer, resolved, depth) {
2096
2266
  { kinds: [pointer.kind], authors: [pointer.pubkey], '#d': [pointer.identifier], limit: 1 },
2097
2267
  // Only when the app actually declares a change kind — see `foldRuleOf`.
2098
2268
  ...(manifest.records ? [{ kinds: [manifest.records.changeKind], '#a': [address], limit: 500 }] : []),
2269
+ // Every file may be archived, including one whose app folds nothing
2270
+ // (FOL-46). SPEC's change kind, when the app has not named its own.
2271
+ ...(manifest.records ? [] : [{ kinds: [ARCHIVE_RULE.changeKind], '#a': [address], limit: 500 }]),
2099
2272
  { kinds: commentKinds, '#a': [address], limit: CONVERSATION_LIMIT },
2100
2273
  ...(childFilter ? [childFilter.filter] : []),
2101
2274
  ];
@@ -2181,6 +2354,7 @@ function assembleObject(plan, answered) {
2181
2354
  viaRecommendation,
2182
2355
  webTemplate: resolved.webTemplate,
2183
2356
  comments,
2357
+ archived: archiveOf(events, address, archiveRuleOf(manifest)),
2184
2358
  });
2185
2359
  /*
2186
2360
  The `list` slot — PRO-7.
@@ -3234,6 +3408,11 @@ function buildOneActionEvent(args) {
3234
3408
  if (args.contentFormat !== undefined && !isCreation && (!declared.emits.field || declared.emits.kind === KIND_DELETION)) {
3235
3409
  return `"${declared.label}" takes no prose value, so it takes no content format.`;
3236
3410
  }
3411
+ // A note is a change's `content`. Anywhere else it would be dropped, and the
3412
+ // resolution a person typed lost without a word.
3413
+ if (args.note !== undefined && (isCreation || !declared.emits.field || declared.emits.kind === KIND_DELETION)) {
3414
+ return `"${declared.label}" is not a change, so it takes no note.`;
3415
+ }
3237
3416
  // An object-creating action is a different event entirely — a new object
3238
3417
  // rather than a change to one — so it branches before the scalar path.
3239
3418
  if (isCreation) {
@@ -3346,7 +3525,7 @@ function buildOneActionEvent(args) {
3346
3525
  created_at: Math.floor(args.createdAtMs / 1000),
3347
3526
  kind: declared.emits.kind,
3348
3527
  tags,
3349
- content: declared.emits.field ? '' : value,
3528
+ content: declared.emits.field ? (args.note ?? '') : value,
3350
3529
  };
3351
3530
  }
3352
3531
  /**
@@ -3405,9 +3584,12 @@ const nameOf = (event) => (event ? tagValue(event, 'name') : undefined);
3405
3584
  *
3406
3585
  * Not a list of ids: a new team is a folder somebody creates, not a code
3407
3586
  * change. Moved here from Peek and Ship, which each held the same line.
3587
+ *
3588
+ * An archived Folder is not navigated by (FOL-46), and a listing that has not
3589
+ * read archives — a summary with no `archived` field — keeps every Folder.
3408
3590
  */
3409
3591
  export function topLevelFolders(folders) {
3410
- return folders.filter((folder) => folder.hasState && !folder.listedIn?.length);
3592
+ return folders.filter((folder) => folder.hasState && !folder.listedIn?.length && !folder.archived);
3411
3593
  }
3412
3594
  /**
3413
3595
  * Every folder this identity can see, for a sidebar.
@@ -3444,6 +3626,12 @@ export async function listFolders(query) {
3444
3626
  ...(addresses.length ? { addresses } : {}),
3445
3627
  });
3446
3628
  }
3629
+ for (const event of events) {
3630
+ const id = tagValue(event, 'd');
3631
+ const folder = id && event.kind === KIND_CHANNEL ? byId.get(id) : undefined;
3632
+ if (folder)
3633
+ folder.channel = pointerToAddress({ kind: KIND_CHANNEL, pubkey: event.pubkey, identifier: id, relays: [] });
3634
+ }
3447
3635
  /*
3448
3636
  A folder listed in another folder's state is a file there. Read off the
3449
3637
  states already in hand: an `a` naming a `kind:39000` is a channel, and its
@@ -3469,14 +3657,172 @@ export async function listFolders(query) {
3469
3657
  listedIn.set(identifier, containers);
3470
3658
  }
3471
3659
  }
3472
- await placeRecordChannels(events, byId, listedIn, query);
3660
+ const { recordsOf, archives } = await placeRecordChannels(events, byId, listedIn, query);
3473
3661
  for (const [id, containers] of listedIn) {
3474
3662
  const folder = byId.get(id);
3475
3663
  if (folder)
3476
3664
  folder.listedIn = containers;
3477
3665
  }
3666
+ markArchivedFolders(byId, recordsOf, archives);
3478
3667
  return [...byId.values()].sort((a, b) => (a.name ?? a.id).localeCompare(b.name ?? b.id));
3479
3668
  }
3669
+ /**
3670
+ * Which Folders are archived — FOL-46, from the changes {@link placeRecordChannels}
3671
+ * read with the record roots.
3672
+ *
3673
+ * A Folder is archived by a change naming its channel's address, the way any
3674
+ * file is. A record's channel — a Ship project's conversation — is archived
3675
+ * with its record, so an archived project's channel stops lighting its team's
3676
+ * dot the way the project stopped being listed — only when every record naming
3677
+ * the channel is archived, since two projects may share one. Its own archive
3678
+ * wins when it has one.
3679
+ *
3680
+ * A refused read throws before this, like the reads beside it: a listing that
3681
+ * silently reported every Folder live would put archived teams back in
3682
+ * everyone's sidebar.
3683
+ */
3684
+ function markArchivedFolders(byId, recordsOf, changes) {
3685
+ for (const folder of byId.values()) {
3686
+ const own = folder.channel ? archiveOf(changes, folder.channel, ARCHIVE_RULE) : undefined;
3687
+ if (own) {
3688
+ folder.archived = own;
3689
+ continue;
3690
+ }
3691
+ const records = recordsOf.get(folder.id) ?? [];
3692
+ const archives = records.map((record) => archiveOf(changes, record, ARCHIVE_RULE));
3693
+ if (records.length && archives.every(Boolean))
3694
+ folder.archived = { ...archives[0], with: records[0] };
3695
+ }
3696
+ }
3697
+ /** How many Folders deep {@link archiveImpact} follows nested Folders. A request per Folder. */
3698
+ const MAX_ARCHIVE_DEPTH = 3;
3699
+ /**
3700
+ * Count what archiving `address` would hide — the read behind the warning.
3701
+ *
3702
+ * "Hides 14 issues and 6 topics that are only here; 2 topics also in Estiva HQ
3703
+ * stay visible." The words are the app's; the counts are the same in every
3704
+ * app, which is why they are read here.
3705
+ *
3706
+ * - **A Folder** (a `kind:39000` address, `FolderSummary.channel`): what it
3707
+ * lists, split by whether another Folder lists it too, the children of what
3708
+ * would be hidden, and — three Folders deep — what a nested Folder only it
3709
+ * lists holds. Pass `folders` from the app's own `listFolders` to save that
3710
+ * read.
3711
+ * - **Any other file**: the children its kind declares (a project's issues), and
3712
+ * bare files placed under it (sub-topics), by their root's `a` tag.
3713
+ *
3714
+ * One level of children, as a listing draws them. A few requests, whatever the
3715
+ * size: the Folder, one per app's manifest (memoised by `cache`), the children,
3716
+ * and their archives.
3717
+ */
3718
+ export async function archiveImpact(address, query, options = {}) {
3719
+ const pointer = addressPointerOf(address);
3720
+ if (!pointer)
3721
+ return { hides: [], staysVisible: [] };
3722
+ const counts = new Map();
3723
+ const count = (kind, n = 1) => counts.set(kind, (counts.get(kind) ?? 0) + n);
3724
+ const staysVisible = [];
3725
+ let parents = [{ address, pointer }];
3726
+ if (pointer.kind === KIND_CHANNEL) {
3727
+ const folders = options.folders ?? (await listFolders(query));
3728
+ parents = [];
3729
+ /*
3730
+ A nested Folder only this one lists goes out of view with it, and so does
3731
+ everything only *that* one lists — walked the same way, a Folder at a
3732
+ time, to a small depth. "Only" is judged against the live Folders outside
3733
+ the tree being archived.
3734
+ */
3735
+ const inTree = new Set([pointer.identifier]);
3736
+ const walk = async (folder, depth) => {
3737
+ const contents = await resolveFolderContents(folder, query, async () => ({}), options.cache);
3738
+ for (const file of contents.files) {
3739
+ if (!file.address)
3740
+ continue;
3741
+ const others = folders.filter((other) => !inTree.has(other.id) && !other.archived && other.addresses?.includes(file.address));
3742
+ if (others.length) {
3743
+ staysVisible.push({ address: file.address, kind: file.kind, in: others.map(({ id, name }) => ({ id, name })) });
3744
+ continue;
3745
+ }
3746
+ count(file.kind);
3747
+ const filePointer = addressPointerOf(file.address);
3748
+ if (!filePointer)
3749
+ continue;
3750
+ if (filePointer.kind === KIND_CHANNEL) {
3751
+ if (depth < MAX_ARCHIVE_DEPTH && !inTree.has(filePointer.identifier)) {
3752
+ inTree.add(filePointer.identifier);
3753
+ await walk(filePointer.identifier, depth + 1);
3754
+ }
3755
+ }
3756
+ else {
3757
+ parents.push({ address: file.address, pointer: filePointer });
3758
+ }
3759
+ }
3760
+ };
3761
+ await walk(pointer.identifier, 0);
3762
+ }
3763
+ // A record channel lists a project *and* its issues; each is counted once.
3764
+ const counted = new Set(parents.map((p) => p.address));
3765
+ for (const [kind, n] of await countLiveChildren(parents, counted, query, options.cache))
3766
+ count(kind, n);
3767
+ return {
3768
+ hides: [...counts].map(([kind, n]) => ({ kind, count: n })),
3769
+ staysVisible,
3770
+ };
3771
+ }
3772
+ /** The children of each parent that are not archived already, by kind. */
3773
+ async function countLiveChildren(parents, counted, query, cache) {
3774
+ const byKind = new Map();
3775
+ if (parents.length === 0)
3776
+ return byKind;
3777
+ const byApp = new Map();
3778
+ for (const { pointer } of parents)
3779
+ byApp.set(manifestKeyOf(pointer), pointer);
3780
+ const manifests = new Map();
3781
+ await Promise.all([...byApp].map(async ([key, pointer]) => {
3782
+ const resolved = await resolveManifest(pointer, query, cache);
3783
+ if (resolved)
3784
+ manifests.set(key, resolved);
3785
+ }));
3786
+ const filters = [];
3787
+ const wanted = [];
3788
+ for (const { address, pointer } of parents) {
3789
+ const projection = manifests.get(manifestKeyOf(pointer))?.manifest.projections?.[String(pointer.kind)];
3790
+ const declared = projection && declaredChildSpec(projection);
3791
+ const specs = [
3792
+ ...(declared ? [{ kind: declared.kind, via: declared.via }] : []),
3793
+ // A sub-topic may sit under a file of any kind (SPEC §6.7).
3794
+ ...(declared?.kind === KIND_BARE_FILE && declared.via === 'a' ? [] : [{ kind: KIND_BARE_FILE, via: 'a' }]),
3795
+ ];
3796
+ for (const spec of specs) {
3797
+ wanted.push({ ...spec, parent: address });
3798
+ filters.push({ kinds: [spec.kind], [`#${spec.via}`]: [address], limit: RELAY_PAGE_CEILING });
3799
+ }
3800
+ }
3801
+ const events = [];
3802
+ for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
3803
+ events.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
3804
+ }
3805
+ const children = new Map();
3806
+ for (const event of events) {
3807
+ const identifier = tagValue(event, 'd');
3808
+ if (identifier === undefined)
3809
+ continue;
3810
+ if (!wanted.some((w) => w.kind === event.kind && hasTagValue(event, w.via, w.parent)))
3811
+ continue;
3812
+ const child = pointerToAddress({ kind: event.kind, pubkey: event.pubkey, identifier, relays: [] });
3813
+ if (!counted.has(child))
3814
+ children.set(child, event.kind);
3815
+ }
3816
+ if (children.size === 0)
3817
+ return byKind;
3818
+ const changes = await readArchiveChanges([...children.keys()], query);
3819
+ for (const [child, kind] of children) {
3820
+ if (archiveOf(changes, child, ARCHIVE_RULE))
3821
+ continue;
3822
+ byKind.set(kind, (byKind.get(kind) ?? 0) + 1);
3823
+ }
3824
+ return byKind;
3825
+ }
3480
3826
  /**
3481
3827
  * A record's own channel is listed wherever the record is (FOL-42).
3482
3828
  *
@@ -3547,8 +3893,18 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3547
3893
  containersOf.set(key, entry);
3548
3894
  }
3549
3895
  }
3550
- if (containersOf.size === 0)
3551
- return;
3896
+ // Every Folder's archive, and every listed record's, ride with the roots
3897
+ // (FOL-46): the channel addresses are in hand from the listing and the
3898
+ // record addresses are the keys above, so neither needs the roots first.
3899
+ const channels = [...byId.values()].flatMap((folder) => (folder.channel ? [folder.channel] : []));
3900
+ const archiveAsk = archiveFilters([...new Set([...channels, ...containersOf.keys()])]);
3901
+ if (containersOf.size === 0) {
3902
+ const archives = [];
3903
+ for (let start = 0; start < archiveAsk.length; start += MAX_FILTERS_PER_QUERY) {
3904
+ archives.push(...(await query(archiveAsk.slice(start, start + MAX_FILTERS_PER_QUERY))));
3905
+ }
3906
+ return { recordsOf: new Map(), archives };
3907
+ }
3552
3908
  const groups = new Map();
3553
3909
  for (const { pointer } of containersOf.values()) {
3554
3910
  const key = `${pointer.kind}:${pointer.pubkey}`;
@@ -3563,10 +3919,14 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3563
3919
  filters.push({ kinds: [kind], authors: [pubkey], '#d': chunk, limit: chunk.length });
3564
3920
  }
3565
3921
  }
3566
- const roots = [];
3922
+ filters.push(...archiveAsk);
3923
+ const answered = [];
3567
3924
  for (let start = 0; start < filters.length; start += MAX_FILTERS_PER_QUERY) {
3568
- roots.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
3925
+ answered.push(...(await query(filters.slice(start, start + MAX_FILTERS_PER_QUERY))));
3569
3926
  }
3927
+ // A state lists files, never change events, so the kind tells them apart.
3928
+ const archives = answered.filter((e) => e.kind === ARCHIVE_RULE.changeKind);
3929
+ const roots = answered.filter((e) => e.kind !== ARCHIVE_RULE.changeKind);
3570
3930
  // Newest wins, as it does for any addressable event a relay has not yet replaced.
3571
3931
  const newest = new Map();
3572
3932
  for (const root of roots) {
@@ -3575,11 +3935,16 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3575
3935
  if (!held || root.created_at > held.created_at)
3576
3936
  newest.set(key, root);
3577
3937
  }
3938
+ const recordsOf = new Map();
3578
3939
  for (const [key, { containers }] of containersOf) {
3579
3940
  const root = newest.get(key);
3580
3941
  const channel = root && folderOf(root);
3581
3942
  if (!channel || byId.get(channel)?.hasState)
3582
3943
  continue;
3944
+ // A file published into the Folder that lists it names that Folder, and
3945
+ // does not own it: a topic's `h` is its team's.
3946
+ if (!containers.includes(channel))
3947
+ recordsOf.set(channel, [...(recordsOf.get(channel) ?? []), key]);
3583
3948
  for (const container of containers) {
3584
3949
  if (container === channel)
3585
3950
  continue;
@@ -3589,6 +3954,7 @@ async function placeRecordChannels(events, byId, listedIn, query) {
3589
3954
  listedIn.set(channel, placed);
3590
3955
  }
3591
3956
  }
3957
+ return { recordsOf, archives };
3592
3958
  }
3593
3959
  /**
3594
3960
  * Everything in one folder, resolved through the manifests of the apps that own it.
@@ -3637,7 +4003,7 @@ export async function resolveFolderContents(folder, query,
3637
4003
  /** Defaults to asking the relay. The browser passes a cached lookup. */
3638
4004
  lookupPeople,
3639
4005
  /** See {@link ProjectionCache}. Omitting it is exactly the old behaviour. */
3640
- cache) {
4006
+ cache, options = {}) {
3641
4007
  // 1. The folder itself. Both kinds in one trip: the state is the model and
3642
4008
  // the channel is what names a folder that has none yet.
3643
4009
  const identity = await query([
@@ -3646,10 +4012,14 @@ cache) {
3646
4012
  ]);
3647
4013
  const state = identity.find((e) => e.kind === KIND_FOLDER_STATE && tagValue(e, 'd') === folder);
3648
4014
  const channel = identity.find((e) => e.kind === KIND_CHANNEL && tagValue(e, 'd') === folder);
4015
+ const channelAddress = channel
4016
+ ? pointerToAddress({ kind: KIND_CHANNEL, pubkey: channel.pubkey, identifier: folder, relays: [] })
4017
+ : undefined;
3649
4018
  const summary = {
3650
4019
  id: folder,
3651
4020
  name: nameOf(state) ?? nameOf(channel),
3652
4021
  hasState: !!state,
4022
+ ...(channelAddress ? { channel: channelAddress } : {}),
3653
4023
  ...(state
3654
4024
  ? { address: pointerToAddress({ kind: state.kind, pubkey: state.pubkey, identifier: folder, relays: [] }) }
3655
4025
  : {}),
@@ -3663,7 +4033,12 @@ cache) {
3663
4033
  }
3664
4034
  : await addressesByContainment(folder, query);
3665
4035
  if (addresses.length === 0) {
3666
- return { ...summary, files: [], source: state ? 'state' : 'channel' };
4036
+ // Nothing listed, so no change query to ride on: the Folder's own archive
4037
+ // is one small read of its own.
4038
+ const archived = channelAddress
4039
+ ? archiveOf(await readArchiveChanges([channelAddress], query), channelAddress, ARCHIVE_RULE)
4040
+ : undefined;
4041
+ return { ...summary, ...(archived ? { archived } : {}), files: [], source: state ? 'state' : 'channel' };
3667
4042
  }
3668
4043
  // 2. Group by (kind, author): one manifest answers for every file an app owns
3669
4044
  // in this folder, and the cache makes the second folder free.
@@ -3702,8 +4077,15 @@ cache) {
3702
4077
  // Change kinds are a set because two apps may fold differently, and a kind
3703
4078
  // is a u16 — the relay refuses an out-of-range one outright, so an app
3704
4079
  // declaring no `records` contributes no filter rather than an empty one.
4080
+ //
4081
+ // SPEC's change kind is always asked for, whatever the apps declare: any
4082
+ // file may be archived (FOL-46), a nested Folder included, and so may this
4083
+ // Folder, whose own address rides in the same filter.
3705
4084
  const changeKinds = [
3706
- ...new Set([...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : []))),
4085
+ ...new Set([
4086
+ ARCHIVE_RULE.changeKind,
4087
+ ...[...manifests.values()].flatMap((r) => (r.manifest.records ? [r.manifest.records.changeKind] : [])),
4088
+ ]),
3707
4089
  ];
3708
4090
  const events = await query([
3709
4091
  ...[...groups.values()].map(({ pointer, addresses: group }) => ({
@@ -3712,12 +4094,21 @@ cache) {
3712
4094
  '#d': group.map((a) => referenceToPointer(a).identifier),
3713
4095
  limit: group.length,
3714
4096
  })),
3715
- ...(changeKinds.length
3716
- ? [{ kinds: changeKinds, '#a': addresses, limit: 500 }]
3717
- : []),
4097
+ { kinds: changeKinds, '#a': addresses, limit: 500 },
4098
+ // The archives again, in groups small enough that a busy Folder's other
4099
+ // changes cannot push them off the page — the filter above holds 500
4100
+ // changes for every file together, and one Folder has already had 688.
4101
+ // Same request.
4102
+ ...archiveFilters(channelAddress ? [...addresses, channelAddress] : addresses),
3718
4103
  ]);
3719
- // 4. Build each file, in the order the folder listed them.
3720
- const files = [];
4104
+ const ownArchive = channelAddress ? archiveOf(events, channelAddress, ARCHIVE_RULE) : undefined;
4105
+ if (ownArchive)
4106
+ summary.archived = ownArchive;
4107
+ // 4. Build each file, in the order the folder listed them. Archived files are
4108
+ // held back until the cascade below has read their parents.
4109
+ const listed = [];
4110
+ const archiveByAddress = new Map();
4111
+ const parentByAddress = new Map();
3721
4112
  for (const { address, pointer } of pointers) {
3722
4113
  const resolved = manifests.get(manifestKeyOf(pointer));
3723
4114
  // No app claims this kind, so there is no projection to draw it with.
@@ -3732,11 +4123,16 @@ cache) {
3732
4123
  continue;
3733
4124
  const records = foldRuleOf(resolved.manifest);
3734
4125
  const folded = foldChanges(events.filter((e) => e.kind === records.changeKind && hasTagValue(e, records.targetTag, address)), records);
4126
+ const archive = archiveOf(events, address, archiveRuleOf(resolved.manifest));
4127
+ archiveByAddress.set(address, archive);
4128
+ parentByAddress.set(address, parentRefOf(resolved.manifest, pointer.kind, root, folded));
3735
4129
  // An app hiding a record from its own lists is saying it is not part of the
3736
- // folder any more. `hiddenWhen` is the app's own declaration of that.
3737
- if (records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals) {
4130
+ // folder any more. `hiddenWhen` is the app's own declaration of that — the
4131
+ // archive above is the same statement for a kind whose app declared none.
4132
+ // Not reported as an archive: the app said "hidden", which may mean more.
4133
+ const hidden = !!records.hiddenWhen && folded[records.hiddenWhen.field]?.value === records.hiddenWhen.equals;
4134
+ if (hidden && !archive)
3738
4135
  continue;
3739
- }
3740
4136
  /*
3741
4137
  A placed file stays listed only while the placement is current.
3742
4138
 
@@ -3762,15 +4158,55 @@ cache) {
3762
4158
  if (!current)
3763
4159
  continue;
3764
4160
  }
3765
- files.push(buildObject({
3766
- root,
3767
- pointer,
3768
- manifest: resolved.manifest,
3769
- projection,
3770
- folded,
3771
- viaRecommendation: resolved.viaRecommendation,
3772
- webTemplate: resolved.webTemplate,
3773
- }));
4161
+ listed.push({
4162
+ archive,
4163
+ file: buildObject({
4164
+ root,
4165
+ pointer,
4166
+ manifest: resolved.manifest,
4167
+ projection,
4168
+ folded,
4169
+ viaRecommendation: resolved.viaRecommendation,
4170
+ webTemplate: resolved.webTemplate,
4171
+ }),
4172
+ });
4173
+ }
4174
+ /*
4175
+ 5. The cascade (FOL-46): a file under an archived file is hidden with it —
4176
+ an issue with its project, a sub-topic with its topic. Computed here and
4177
+ never written to the children, so unarchiving the parent restores
4178
+ exactly what was there.
4179
+
4180
+ The chain is walked through everything this Folder lists. A parent that
4181
+ lives in another Folder is read once for all such parents, one level: a
4182
+ project whose record channel lists its issues is the case that matters,
4183
+ and there the project is listed too.
4184
+
4185
+ Only by parent. A file this Folder lists is never hidden because some
4186
+ *other* Folder that lists it is archived — that is what lets a file
4187
+ placed in two Folders stay visible in the one that is not archived.
4188
+ */
4189
+ const outside = [
4190
+ ...new Set(listed.flatMap(({ file }) => {
4191
+ const parent = file.address && parentByAddress.get(file.address);
4192
+ return parent && !archiveByAddress.has(parent) && addressPointerOf(parent) ? [parent] : [];
4193
+ })),
4194
+ ];
4195
+ if (outside.length) {
4196
+ const changes = await readArchiveChanges(outside, query);
4197
+ for (const parent of outside)
4198
+ archiveByAddress.set(parent, archiveOf(changes, parent, ARCHIVE_RULE));
4199
+ }
4200
+ const files = [];
4201
+ for (const { file, archive } of listed) {
4202
+ const effective = archive ??
4203
+ (file.address
4204
+ ? archivedAncestorOf(file.address, (a) => parentByAddress.get(a), (a) => archiveByAddress.get(a))
4205
+ : undefined);
4206
+ if (!effective)
4207
+ files.push(file);
4208
+ else if (options.includeArchived)
4209
+ files.push({ ...file, archived: effective });
3774
4210
  }
3775
4211
  const people = await (lookupPeople ?? peopleViaRelay(query))([
3776
4212
  ...new Set(files.flatMap(pubkeysIn)),