@estiva-app/interop 0.108.0 → 0.109.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/src/projection.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { decodeNevent, encodeNaddr, encodeNevent, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
16
  import { parseProfile, type Profile, type SignedEvent } from '@estiva-app/protocol'
17
- import { FILE_KINDS, MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING, fileIdFormOf } from '@estiva-app/protocol'
17
+ import { BASE_TYPE_OF_KIND, FILE_KINDS, MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING, fileIdFormOf } from '@estiva-app/protocol'
18
18
  import {
19
19
  attachmentsInDocument,
20
20
  BLOCK_DOCUMENT_FORMAT,
@@ -1612,8 +1612,9 @@ const BARE_FILE_MANIFEST: Manifest = {
1612
1612
  id: 'delete',
1613
1613
  label: 'Delete',
1614
1614
  description:
1615
- 'Ask the relay to delete this file. The relay decides — only its author, or the owner of ' +
1616
- 'an agent that wrote it, may — and its comments stay as separate events.',
1615
+ 'Delete this file. Where the relay keeps topics in order it is marked deleted, by anyone in its team, ' +
1616
+ 'stays on its lists and can be restored; elsewhere the relay is asked to delete it and decides — only ' +
1617
+ 'its author, or the owner of an agent that wrote it, may. Its comments stay as separate events.',
1617
1618
  effect: 'destructive',
1618
1619
  appliesTo: [String(KIND_BARE_FILE)],
1619
1620
  /*
@@ -2385,7 +2386,7 @@ type FoldedField = { value: string; format?: ContentFormat; stage?: Stage }
2385
2386
  *
2386
2387
  * Built once per root, and asked once per change.
2387
2388
  */
2388
- function targetFolders(root: SignedEvent | undefined): ReadonlySet<string> | undefined {
2389
+ export function targetFolders(root: SignedEvent | undefined): ReadonlySet<string> | undefined {
2389
2390
  if (!root) return undefined
2390
2391
  const folders = new Set(PLACEMENTS.flatMap((name) => root.tags.filter((t) => t[0] === name && t[1]).map((t) => t[1]!)))
2391
2392
  if (root.kind === KIND_CHANNEL_METADATA) {
@@ -2395,7 +2396,7 @@ function targetFolders(root: SignedEvent | undefined): ReadonlySet<string> | und
2395
2396
  return folders.size ? folders : undefined
2396
2397
  }
2397
2398
 
2398
- function inTargetFolder(change: SignedEvent, folders: ReadonlySet<string> | undefined): boolean {
2399
+ export function inTargetFolder(change: SignedEvent, folders: ReadonlySet<string> | undefined): boolean {
2399
2400
  if (!folders) return true
2400
2401
  // The first `h` with a value, as the relay reads it: an empty `["h"]` ahead
2401
2402
  // of a real one must not make this read a different Folder from the one the
@@ -2595,7 +2596,10 @@ function archiveOf(
2595
2596
  root: SignedEvent | undefined,
2596
2597
  folderAdmins?: ReadonlySet<string>,
2597
2598
  ): Archive | undefined {
2598
- const [kind, , identifier] = address.split(':')
2599
+ // The `d` is everything after the pubkey: an id may hold a colon, and cutting
2600
+ // it there dropped every archive whose `O` named the whole id (TES-2).
2601
+ const [kind, , ...rest] = address.split(':')
2602
+ const identifier = rest.join(':')
2599
2603
  if (Number(kind) === KIND_CHANNEL) {
2600
2604
  if (!folderAdmins?.size) return undefined
2601
2605
  changes = changes.filter((change) => tagValue(change, 'h') === identifier && folderAdmins.has(change.pubkey))
@@ -3548,6 +3552,8 @@ function buildObject(args: {
3548
3552
 
3549
3553
  /** The field a file is deleted by (SPEC §6.5): `true` deletes it, the empty value restores it. */
3550
3554
  const DELETED_FIELD = 'deleted'
3555
+ /** A file's change (§6.2): what a Delete on a file kept in order is written as, whatever a listing names. */
3556
+ const KIND_FILE_CHANGE = 1851
3551
3557
 
3552
3558
  /**
3553
3559
  * An addressable file's actions, each with what its field holds now, however
@@ -6546,12 +6552,29 @@ export interface ActionEventArgs {
6546
6552
  */
6547
6553
  export function buildActionEvent(args: ActionEventArgs): UnsignedActionEvent | string {
6548
6554
  const declared = args.manifest.actions?.find((a) => a.id === args.actionId)
6555
+ if (declared && marksDeleted(declared, args)) return buildOneActionEvent(args)
6549
6556
  if (declared?.emits.listed === true && (declared.emits.kind === KIND_DELETION || isCreationAction(declared))) {
6550
6557
  return `"${declared.label}" is followed by a team command, so it is built with buildActionEvents.`
6551
6558
  }
6552
6559
  return buildOneActionEvent(args)
6553
6560
  }
6554
6561
 
6562
+ /**
6563
+ * Whether an older listing's Delete, declared as a `kind:5`, is written as
6564
+ * the file's `deleted` change instead (SPEC §7.3, §6.5): on a file whose type
6565
+ * the relay keeps in order (`args.inOrder`), which refuses a `kind:5` on it.
6566
+ * That change marks the file only — nothing is taken off a team's list — and
6567
+ * a restore is the same field set back to empty (`setDeleted`). A Delete
6568
+ * declared as the `deleted` field is already a change, built as one.
6569
+ *
6570
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-file-type-is-kept-in-order-and-a-delete-only-marks-the-file.md
6571
+ */
6572
+ function marksDeleted(declared: ManifestAction, args: Pick<ActionEventArgs, 'inOrder' | 'kind'>): boolean {
6573
+ // By the file's type, not the shape of its id: the relay refuses a `kind:5` on any file of a type it keeps in order.
6574
+ const type = BASE_TYPE_OF_KIND[args.kind]
6575
+ return declared.emits.kind === KIND_DELETION && type !== undefined && (args.inOrder ?? []).includes(type)
6576
+ }
6577
+
6555
6578
  /** An action that makes a new object rather than changing one — a form. */
6556
6579
  function isCreationAction(declared: ManifestAction): boolean {
6557
6580
  return declared.input?.type === 'object' && !!declared.input.properties
@@ -6584,7 +6607,8 @@ export function buildActionEvents(
6584
6607
  const first = buildOneActionEvent(args)
6585
6608
  if (typeof first === 'string') return first
6586
6609
  const declared = args.manifest.actions!.find((a) => a.id === args.actionId)!
6587
- if (declared.emits.listed !== true) return [first]
6610
+ // A delete that marks the file takes it off no team's list, so a restore brings back exactly what was there.
6611
+ if (declared.emits.listed !== true || marksDeleted(declared, args)) return [first]
6588
6612
 
6589
6613
  if (declared.emits.kind === KIND_DELETION) {
6590
6614
  if (!args.listedIn) return `"${declared.label}" unlists what it deletes, and needs the teams that list it.`
@@ -6624,6 +6648,21 @@ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | strin
6624
6648
  return `"${declared.label}" does not apply to a kind ${kind}.`
6625
6649
  }
6626
6650
 
6651
+ // A `kind:5` Delete on a file kept in order: built as its `deleted` change, `true`, whatever the confirm passed (§7.3).
6652
+ if (marksDeleted(declared, args)) {
6653
+ if (replyTo) return `"${declared.label}" is not a comment, so it cannot reply to one.`
6654
+ if (args.prev === undefined) return `"${declared.label}" follows the file's last delete or restore, or its first record: pass its prev.`
6655
+ if (!records) return 'That app does not say how its records are written.'
6656
+ // A file's change is a `kind:1851` (§6.2): never the kind a listing names, which could be a `kind:5` again or a profile.
6657
+ if (records.changeKind !== KIND_FILE_CHANGE) return `"${declared.label}" is written as a kind ${KIND_FILE_CHANGE} change, which that app does not say it writes.`
6658
+ const asChange: ManifestAction = { ...declared, emits: { kind: KIND_FILE_CHANGE, field: DELETED_FIELD }, input: { type: 'string' } }
6659
+ return buildOneActionEvent({
6660
+ ...args,
6661
+ value: 'true',
6662
+ manifest: { ...manifest, actions: (manifest.actions ?? []).map((a) => (a === declared ? asChange : a)) },
6663
+ })
6664
+ }
6665
+
6627
6666
  const isCreation = isCreationAction(declared)
6628
6667
 
6629
6668
  // A reply is a comment with a parent — what the scalar path below builds for
@@ -30,6 +30,7 @@ export type FileLook = 'row' | 'card'
30
30
 
31
31
  const ORDER = 'order:'
32
32
  const LOOK = 'look:'
33
+ const LISTS = 'lists:'
33
34
  /** The field a file's place on a topic is kept in: `order:<d>`. */
34
35
  export const orderField = (file: string): string => `${ORDER}${file}`
35
36
  /** The field a file's look on a topic is kept in: `look:<d>`. */
@@ -107,7 +108,16 @@ export interface FileArrangement {
107
108
  * on the relay, one a reader skips included (the relay chains them all),
108
109
  * or the topic's first record when the field never changed.
109
110
  */
110
- prev: { order: string; look: string }
111
+ prev: {
112
+ order: string
113
+ look: string
114
+ /**
115
+ * Its entry on the list, `lists:<d>`: what taking it off follows where
116
+ * the relay keeps topics in order (`planRemoveFromTopic`'s `prev`).
117
+ * Optional only so an arrangement built by hand still type-checks.
118
+ */
119
+ lists?: string
120
+ }
111
121
  /** The latest time (ms) among those, so a change is stamped after it. */
112
122
  prevAt: number
113
123
  }
@@ -166,12 +176,14 @@ export function arrangementHeads(
166
176
  const list = tagOf(event, 'a')
167
177
  if (!list) continue
168
178
  for (const { field } of fieldsSetBy(event)) {
169
- if (!isArrangeField(field)) continue
179
+ const isEntry = field.startsWith(LISTS)
180
+ if (!isArrangeField(field) && !isEntry) continue
170
181
  const heads = out.get(list) ?? { good: new Map(), any: new Map() }
171
182
  out.set(list, heads)
172
183
  const held = heads.any.get(field)
173
184
  if (!held || byOrder(held, event) < 0) heads.any.set(field, event)
174
- if (!readsAs(event, field, list, teamOfList(list))) continue
185
+ // An entry is folded by `listEntries`; here only its head is kept, as the next `prev`.
186
+ if (isEntry || !readsAs(event, field, list, teamOfList(list))) continue
175
187
  const good = heads.good.get(field)
176
188
  if (!good || byOrder(good, event) < 0) heads.good.set(field, event)
177
189
  }
@@ -193,10 +205,12 @@ export function arrangementOf(heads: Heads | undefined, file: string, listed: Si
193
205
  const look = looked ? valueIn(looked, lookField(file)) : undefined
194
206
  const orderHead = heads?.any.get(orderField(file))
195
207
  const lookHead = heads?.any.get(lookField(file))
208
+ // The relay chains every entry, one a reader skips included; `listed` is the newest one that counts.
209
+ const listsHead = heads?.any.get(`${LISTS}${file}`) ?? listed
196
210
  return {
197
211
  ...(isPlaceKey(key) ? { order: key } : {}),
198
212
  ...(look === 'row' || look === 'card' ? { look } : {}),
199
- prev: { order: orderHead?.id ?? root.id, look: lookHead?.id ?? root.id },
213
+ prev: { order: orderHead?.id ?? root.id, look: lookHead?.id ?? root.id, lists: listsHead.id },
200
214
  prevAt: Math.max(changedAt(root), orderHead ? changedAt(orderHead) : 0, lookHead ? changedAt(lookHead) : 0),
201
215
  }
202
216
  }
@@ -322,15 +336,20 @@ export function planLookInTopic(
322
336
  * over the list read again, so a refusal plans the move again rather than
323
337
  * leaving the file back but last. The move is stamped after the listing, so
324
338
  * its place is not older than it.
339
+ *
340
+ * `listsPrev`, where the relay keeps topics in order, is the change the
341
+ * listing follows: the Remove it undoes (the id the relay accepted), not the
342
+ * file's `prev.lists`, which was read before it.
325
343
  */
326
344
  export function planPutBackInTopic(
327
345
  pubkey: string,
328
346
  createdAtMs: number,
329
- args: { topic: ArrangeHolder; file: ArrangedFile; after: string | null },
347
+ args: { topic: ArrangeHolder; file: ArrangedFile; after: string | null; listsPrev?: string },
330
348
  ): { relist: UnsignedEvent; move: (files: readonly ArrangedFile[], createdAtMs: number) => UnsignedEvent | null } {
331
349
  const listedAt = stamp(createdAtMs, [args.file])
332
350
  const holder = ADDRESS.exec(args.topic.address)
333
351
  if (!holder) throw new Error(`not a file address: ${JSON.stringify(args.topic.address)}`)
352
+ if (args.listsPrev !== undefined && !/^[0-9a-f]{64}$/.test(args.listsPrev)) throw new Error(`not an event id: ${JSON.stringify(args.listsPrev)}`)
334
353
  const relist: UnsignedEvent = {
335
354
  pubkey,
336
355
  created_at: Math.floor(listedAt / 1000),
@@ -342,11 +361,12 @@ export function planPutBackInTopic(
342
361
  ['value', 'true'],
343
362
  ['h', args.topic.folder],
344
363
  ['ts', String(listedAt)],
364
+ ...(args.listsPrev ? [['prev', args.listsPrev]] : []),
345
365
  ['o', args.file.file],
346
366
  ],
347
367
  content: '',
348
368
  }
349
- const move = (files: readonly ArrangedFile[], ms: number) => {
369
+ const move =(files: readonly ArrangedFile[], ms: number) => {
350
370
  // Back on the list it has no place yet; a list read before the listing landed does not hold it.
351
371
  const held = files.find((f) => f.file === args.file.file)
352
372
  const back: ArrangedFile = { ...(held ?? args.file), order: undefined, prevAt: Math.max((held ?? args.file).prevAt, listedAt) }
package/src/topics.ts CHANGED
@@ -5,8 +5,9 @@
5
5
  * A topic lists files from any Folder, one entry per file, by the file's id.
6
6
  * An entry is a `kind:1851` change on the topic: `a` and `O` name the topic,
7
7
  * `field` is `lists:<d>`, `value` is `true` or `false`, `h` is the topic's
8
- * Folder, then `ts`, then `["o", <d>]` naming the listed file. The newest
9
- * entry per topic and file counts (§6.3).
8
+ * Folder, then `ts`, then — where the relay keeps topics in order — `prev`,
9
+ * the change it follows (§6.13), then `["o", <d>]` naming the listed file.
10
+ * The newest entry per topic and file counts (§6.3).
10
11
  *
11
12
  * `O` is the file the change is about and `o` another file it points at
12
13
  * (why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-change-is-about-its-file-as-a-comment-is.md),
@@ -84,10 +85,27 @@ export interface ListHolder {
84
85
  folder: string
85
86
  }
86
87
 
88
+ /**
89
+ * What a list entry is handed. `prev` is the change it follows (§6.13): the
90
+ * newest `lists:<d>` change on the topic for that file, or the topic's first
91
+ * record when the file was never on it — a listed file's `prev.lists` from
92
+ * {@link topicList}, or `prevsAfterSwitch(query, topic, [listsField(file)])`.
93
+ * Pass it where the relay keeps topics in order (`fileFieldsOf(reads,
94
+ * TOPIC_TYPE, …)`), and send through `writeChange` so a stale one is followed
95
+ * again; leave it out elsewhere, and the entry is written as before. Two
96
+ * people adding different files never clash: each file is its own field.
97
+ */
98
+ export interface ListEntryArgs {
99
+ topic: ListHolder
100
+ file: string
101
+ note?: string
102
+ prev?: string
103
+ }
104
+
87
105
  function entry(
88
106
  pubkey: string,
89
107
  createdAtMs: number,
90
- args: { list: ListHolder; file: string; listed: boolean; note?: string },
108
+ args: { list: ListHolder; file: string; listed: boolean; note?: string; prev?: string },
91
109
  ): UnsignedEvent {
92
110
  const holder = ADDRESS.exec(args.list.address)
93
111
  if (!holder) throw new Error(`not a file address: ${JSON.stringify(args.list.address)}`)
@@ -96,6 +114,7 @@ function entry(
96
114
  // A reader ignores a file on its own list (§6.14): refuse it here rather than publish an entry that shows nothing.
97
115
  if (args.file === holder[3]) throw new Error('a file is not on its own list')
98
116
  if (!Number.isSafeInteger(createdAtMs) || createdAtMs < 0) throw new Error(`not epoch milliseconds: ${createdAtMs}`)
117
+ if (args.prev !== undefined && !/^[0-9a-f]{64}$/.test(args.prev)) throw new Error(`not an event id: ${JSON.stringify(args.prev)}`)
99
118
  return {
100
119
  pubkey,
101
120
  created_at: Math.floor(createdAtMs / 1000),
@@ -107,6 +126,8 @@ function entry(
107
126
  ['value', args.listed ? 'true' : 'false'],
108
127
  ['h', args.list.folder],
109
128
  ['ts', String(createdAtMs)],
129
+ // Where `order:` and `look:` carry theirs (§6.14).
130
+ ...(args.prev ? [['prev', args.prev]] : []),
110
131
  ['o', args.file],
111
132
  ],
112
133
  // Empty unless the person wrote a note: each app says "added" and "removed" in its own words (§6.14).
@@ -118,21 +139,13 @@ function entry(
118
139
  * Put a file on a topic's list: `[kind:1851 lists:<d> = true]`, signed by
119
140
  * whoever adds it. `file` is the listed file's id (its `d`), from any Folder.
120
141
  */
121
- export function planListInTopic(
122
- pubkey: string,
123
- createdAtMs: number,
124
- args: { topic: ListHolder; file: string; note?: string },
125
- ): UnsignedEvent[] {
126
- return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: true, note: args.note })]
142
+ export function planListInTopic(pubkey: string, createdAtMs: number, args: ListEntryArgs): UnsignedEvent[] {
143
+ return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: true, note: args.note, prev: args.prev })]
127
144
  }
128
145
 
129
146
  /** Take a file off a topic's list: `[kind:1851 lists:<d> = false]`. {@link planListInTopic} in reverse. */
130
- export function planRemoveFromTopic(
131
- pubkey: string,
132
- createdAtMs: number,
133
- args: { topic: ListHolder; file: string; note?: string },
134
- ): UnsignedEvent[] {
135
- return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: false, note: args.note })]
147
+ export function planRemoveFromTopic(pubkey: string, createdAtMs: number, args: ListEntryArgs): UnsignedEvent[] {
148
+ return [entry(pubkey, createdAtMs, { list: args.topic, file: args.file, listed: false, note: args.note, prev: args.prev })]
136
149
  }
137
150
 
138
151
  /** Which topics list a file: every entry naming its id in `o`. Fold with {@link listEntries}. */