@estiva-app/interop 0.104.0 → 0.106.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/interop",
3
- "version": "0.104.0",
3
+ "version": "0.106.0",
4
4
  "description": "Render and act on another app's objects from its published NIP-89 manifest. The owner defines the projection; the consumer decides how it looks.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -48,11 +48,11 @@
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@estiva-app/conversation": ">=0.34.0",
51
- "@estiva-app/protocol": ">=0.59.0"
51
+ "@estiva-app/protocol": ">=0.60.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@estiva-app/conversation": ">=0.34.0",
55
- "@estiva-app/protocol": ">=0.59.0",
55
+ "@estiva-app/protocol": ">=0.60.0",
56
56
  "typescript": "~5.9.3"
57
57
  }
58
58
  }
package/src/activity.ts CHANGED
@@ -40,7 +40,8 @@
40
40
  import { fileIdOf, RELAY_PAGE_CEILING, type FileTimes, type LiveRelay, type SignedEvent } from '@estiva-app/protocol'
41
41
  import { isAbout, KIND_COMMENT } from '@estiva-app/conversation'
42
42
  import { folderOf, KIND_MESSAGE, type QueryFn } from './projection.js'
43
- import { answeredByEach, answers, firstPages, nextPages, type ReadTopic } from './topics.js'
43
+ import { answeredByEach, answers, firstPages, nextPages, readAll, type ReadTopic } from './topics.js'
44
+ import { fieldsSetBy } from './fields.js'
44
45
  import { LISTED_WATCH_REBUILD_MS, MAX_FILTERS_PER_REQ, openWhenKnown } from './listedConversations.js'
45
46
 
46
47
  const KIND_CHANGE = 1851
@@ -439,10 +440,10 @@ export async function readTopicActivity(
439
440
  const held = newest.get(entry.a)
440
441
  if (!held || entry.created_at > held.created_at) newest.set(entry.a, entry)
441
442
  }
443
+ const placed = await placeMoved(query, read, level, newest)
442
444
  const perParent = new Map<string, number>()
443
445
  const next: string[] = []
444
- for (const entry of [...newest.values()].sort((a, b) => b.created_at - a.created_at)) {
445
- const parent = entry.under!
446
+ for (const { entry, parent } of [...placed.values()].sort((a, b) => b.entry.created_at - a.entry.created_at)) {
446
447
  const taken = perParent.get(parent) ?? 0
447
448
  if (taken >= MAX_CHILDREN) continue
448
449
  perParent.set(parent, taken + 1)
@@ -540,6 +541,73 @@ export type TimesFn = (filters: Record<string, unknown>[]) => Promise<FileTimes[
540
541
  const TIMES_PAGE = RELAY_PAGE_CEILING
541
542
  const MAX_TIMES_PAGES = 20
542
543
 
544
+ /** The field that moves a child to another parent, by the child's kind (§6.7's `movedBy`): an issue's `project`. */
545
+ const MOVED_BY: Readonly<Record<number, string>> = { [KIND_ISSUE]: 'project' }
546
+
547
+ /**
548
+ * Each file the times read found under one of `level`, placed under the
549
+ * parent it is in now (SPEC §6.7, "A `#via` read cannot see a move"): the
550
+ * times read's `under` is the parent its first record names, so a file moved
551
+ * since is placed by its current `movedBy` change instead — under its new
552
+ * parent when that is in `level`, and nowhere here when it is not. A file
553
+ * moved in from elsewhere is found by the `A` its move carries, and kept
554
+ * only when that move is still its current one.
555
+ *
556
+ * Reads: the moves naming a parent in `level`, the current move of each
557
+ * found file whose times show one, and the times of each file moved in;
558
+ * none when nothing under `level` can move.
559
+ */
560
+ async function placeMoved(
561
+ query: QueryFn,
562
+ read: TimesFn,
563
+ level: readonly string[],
564
+ found: ReadonlyMap<string, FileTimes>,
565
+ ): Promise<Map<string, { entry: FileTimes; parent: string }>> {
566
+ const placed = new Map([...found].map(([a, entry]) => [a, { entry, parent: entry.under! }]))
567
+ const movable = level.filter((parent) => (CHILD_KINDS[kindOf(parent)!] ?? []).some((kind) => MOVED_BY[kind]))
568
+ if (movable.length === 0) return placed
569
+ const here = new Set(level)
570
+
571
+ const moves = new Map<string, SignedEvent>()
572
+ for (const event of await readAll(query, chunked(movable, VALUES_PER_FILTER).map((values) => ({ kinds: [KIND_CHANGE], '#A': values })))) {
573
+ moves.set(event.id, event)
574
+ }
575
+ // The files moved in that the walk did not find under the same level: their times, by their `d`.
576
+ const movedIn = new Map<number, Set<string>>()
577
+ for (const move of moves.values()) {
578
+ const file = tagValues(move, 'a')[0]
579
+ const kind = file === undefined ? undefined : kindOf(file)
580
+ if (!file || kind === undefined || !MOVED_BY[kind] || found.has(file)) continue
581
+ movedIn.set(kind, (movedIn.get(kind) ?? new Set()).add(idOf(file)!))
582
+ }
583
+ const candidates = new Map(found)
584
+ const asking = [...movedIn].flatMap(([kind, ds]) => chunked([...ds], VALUES_PER_FILTER).map((values) => ({ fields: 'times', kinds: [kind], '#d': values })))
585
+ for (const entry of asking.length > 0 ? await read(asking) : []) {
586
+ const held = candidates.get(entry.a)
587
+ if (!held || entry.created_at > held.created_at) candidates.set(entry.a, entry)
588
+ }
589
+
590
+ // Each candidate's current move, read whole only when it is not one of the moves already in hand.
591
+ const currentMove = (entry: FileTimes) => {
592
+ const field = MOVED_BY[kindOf(entry.a) ?? -1]
593
+ return field ? entry.changes.find((change) => change.fields.includes(field)) : undefined
594
+ }
595
+ const unread = [...candidates.values()].map(currentMove).filter((c): c is FileTimes['changes'][number] => !!c && !moves.has(c.id)).map((c) => c.id)
596
+ for (const ids of chunked(unread, VALUES_PER_FILTER)) for (const event of await query([{ ids }])) moves.set(event.id, event)
597
+
598
+ for (const [a, entry] of candidates) {
599
+ const change = currentMove(entry)
600
+ const event = change && moves.get(change.id)
601
+ const field = MOVED_BY[kindOf(a) ?? -1]
602
+ const set = event && fieldsSetBy(event).find((f) => f.field === field)
603
+ // No move, or one that could not be read: the first record's parent stands.
604
+ const parent = set ? set.value : entry.under
605
+ if (parent && here.has(parent)) placed.set(a, { entry, parent })
606
+ else placed.delete(a)
607
+ }
608
+ return placed
609
+ }
610
+
543
611
  /** The files under the given ones, by the times read, every page of each filter. */
544
612
  async function timesUnder(read: TimesFn, parents: readonly string[]): Promise<FileTimes[]> {
545
613
  const kinds = [...new Set(parents.flatMap((address) => CHILD_KINDS[kindOf(address)!]!))]
package/src/fields.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  type SignedEvent,
32
32
  type UnsignedEvent,
33
33
  } from '@estiva-app/protocol'
34
+ import { refusalCode } from './folders.js'
34
35
  import { folderOf, type QueryFn } from './projection.js'
35
36
 
36
37
  /** The change event every Estiva app writes (SPEC §6.2). */
@@ -196,12 +197,15 @@ export function textOf(event: SignedEvent): MergeText | undefined {
196
197
  * NIP-11. Read it again, switch, and write the change again in order
197
198
  * ({@link prevsAfterSwitch}): the person sees nothing (Miky, 9 Nov, ALO-8).
198
199
  *
199
- * Decided on the relay's words after `invalid:`, never on what follows them,
200
- * so a relay that adds what to do keeps being recognised.
200
+ * Decided by its reason code, `requires-prev` (§3.3), or, from a relay that
201
+ * predates the code (a project's refusal until ISS-8), by its words after
202
+ * `invalid:`; never on what follows them, so a relay that adds what to do
203
+ * keeps being recognised.
201
204
  *
202
205
  * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-file-is-its-fields-each-kept-in-order-by-the-relay.md
203
206
  */
204
207
  export function isSwitchRefusal(reason: string | undefined): boolean {
208
+ if (refusalCode(reason) === 'requires-prev') return true
205
209
  return !!reason && /^invalid: an? \w+ change names the change it follows in prev\b/.test(reason)
206
210
  }
207
211
 
@@ -577,3 +581,163 @@ export async function writeChanges(args: WriteChangesArgs): Promise<WriteChangeR
577
581
  }
578
582
  return { ok: false, refused: `still refused after ${tries} tries: ${last}` }
579
583
  }
584
+
585
+ /** The field a file is deleted by (SPEC §6.5): `true` deletes it, the empty value restores it. */
586
+ export const DELETED_FIELD = 'deleted'
587
+
588
+ /** What {@link setDeleted} is handed: {@link WriteChangeArgs} for the `deleted` field, `prev` its current change or the first record's id. */
589
+ export interface SetDeletedArgs extends Omit<WriteChangeArgs, 'field' | 'value' | 'format' | 'base'> {
590
+ deleted: boolean
591
+ }
592
+
593
+ /**
594
+ * Delete a file, or restore it, of any type (SPEC §6.5): a change setting
595
+ * `deleted` to `true`, or to the empty value, after the one it follows, which
596
+ * anyone who may edit the file may write. The file keeps its id, first record
597
+ * and every change, so a restore brings it back whole, its issue number
598
+ * included; nothing else is written, and no `kind:5` is sent. Two people
599
+ * deleting and restoring at once: the later stands, as for any field.
600
+ *
601
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-file-is-its-fields-each-kept-in-order-by-the-relay.md
602
+ */
603
+ export function setDeleted(args: SetDeletedArgs): Promise<WriteChangeResult> {
604
+ const { deleted, ...write } = args
605
+ return writeChange({ ...write, field: DELETED_FIELD, value: deleted ? 'true' : '' })
606
+ }
607
+
608
+ /** A {@link writeChange} that saved nothing. */
609
+ export type WriteChangeFailure = Extract<WriteChangeResult, { ok: false }>
610
+
611
+ /** What {@link createFile} and {@link finishCreating} are handed. */
612
+ export interface CreateFileArgs {
613
+ /** The first record, unsigned: what the file is (id, type, team, title, parent, ref, key, summary), and no text. */
614
+ root: UnsignedEvent
615
+ /** The text given at creation, written as the file's first change. None, or an empty one, writes no text. */
616
+ text?: MergeText
617
+ /** Any other first value that is not on the first record (a status, an assignee), written after the text, with no text. */
618
+ others?: readonly { field: string; value: string }[]
619
+ /** The types the relay keeps in order (`RelayFileReads.inOrder`): several other values go in one change only for these. */
620
+ inOrder: readonly string[]
621
+ /** The unsigned one-field change for one field, as {@link WriteChangeArgs.build}: `buildActionEvent` bound to that field's action. */
622
+ build: (input: { field: string; value: string; format?: string; prev: string; createdAtMs: number }) => UnsignedEvent | string
623
+ sign: WriteChangeArgs['sign']
624
+ publish: WriteChangeArgs['publish']
625
+ query: QueryFn
626
+ current: WriteChangeArgs['current']
627
+ now?: () => number
628
+ tries?: number
629
+ }
630
+
631
+ /** What {@link createFile} and {@link finishCreating} answer. */
632
+ export type CreateFileResult =
633
+ | {
634
+ ok: true
635
+ root: SignedEvent
636
+ address: string
637
+ /** Each field written, by the change it now follows: its next `prev`. */
638
+ heads: Record<string, string>
639
+ }
640
+ /** Nothing was created: the first record was refused or never answered. */
641
+ | { ok: false; created: false; refused: string }
642
+ /**
643
+ * The file exists, but `field` (its text, or another first value) did not
644
+ * land. Keep the person's words, never say "created", and hand the same
645
+ * first record to {@link finishCreating} to send the rest again.
646
+ */
647
+ | { ok: false; created: true; root: SignedEvent; address: string; field: string; failed: WriteChangeFailure }
648
+
649
+ const BASE_KINDS = new Set(Object.keys(BASE_TYPE_OF_KIND).map(Number))
650
+
651
+ /** Whether a first record carries text, which a new one never does (§6.1): a `description` tag, a `set` of it, or a base type's `content`. */
652
+ function carriesText(root: UnsignedEvent): boolean {
653
+ if (root.tags.some((t) => t[0] === TEXT_FIELD || (t[0] === 'set' && t[1] === TEXT_FIELD))) return true
654
+ return BASE_KINDS.has(root.kind) && root.content !== ''
655
+ }
656
+
657
+ /**
658
+ * Create a file of any type as SPEC §6.1 says: its first record, carrying no
659
+ * text, then its text as its own one-field change whose `prev` is the first
660
+ * record's id, then any other first value in a change with no text. A first
661
+ * record that carries text is refused here, before anything is sent: the
662
+ * relay refuses it too (`text-is-a-change`) wherever it keeps the type in order.
663
+ *
664
+ * Creating is two writes. Until the text lands the file exists with no text:
665
+ * the answer says so (`created: true`, `ok: false`), and the app keeps the
666
+ * words and sends them again with {@link finishCreating}, never the first
667
+ * record, which is written once.
668
+ *
669
+ * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-new-files-text-is-its-first-change.md
670
+ */
671
+ export async function createFile(args: CreateFileArgs): Promise<CreateFileResult> {
672
+ if (carriesText(args.root)) {
673
+ return { ok: false, created: false, refused: "A new file's first record carries no text: its text is its first change (SPEC §6.1). Nothing was sent." }
674
+ }
675
+ let root: SignedEvent
676
+ try {
677
+ root = await args.sign(args.root)
678
+ const answer = await args.publish(root)
679
+ if (!answer.ok) return { ok: false, created: false, refused: answer.reason ?? 'refused with no reason' }
680
+ } catch (error) {
681
+ return { ok: false, created: false, refused: error instanceof Error ? error.message : String(error) }
682
+ }
683
+ return finishCreating(args, root)
684
+ }
685
+
686
+ /**
687
+ * The writes after a first record: the text, then the other first values,
688
+ * each following the first record (§6.2). Sent again after a failure, it
689
+ * writes what is missing: a text that landed meanwhile, the creator's own or
690
+ * someone's, is merged onto with an empty base, so no words are lost, and a
691
+ * value set again after one already there stands as the later.
692
+ */
693
+ export async function finishCreating(args: Omit<CreateFileArgs, 'root'>, root: SignedEvent): Promise<CreateFileResult> {
694
+ const address = addressOfRoot(root)
695
+ const heads: Record<string, string> = {}
696
+ const unfinished = (field: string, failed: WriteChangeFailure): CreateFileResult => ({ ok: false, created: true, root, address, field, failed })
697
+ const common = { sign: args.sign, publish: args.publish, query: args.query, current: args.current, ...(args.now ? { now: args.now } : {}), ...(args.tries ? { tries: args.tries } : {}) }
698
+ const one = async (field: string, value: string, format?: string): Promise<WriteChangeResult> => {
699
+ try {
700
+ return await writeChange({
701
+ ...common,
702
+ field,
703
+ value,
704
+ ...(format ? { format } : {}),
705
+ prev: root.id,
706
+ build: (input) => args.build({ field, ...input }),
707
+ })
708
+ } catch (error) {
709
+ return { ok: false, refused: error instanceof Error ? error.message : String(error) }
710
+ }
711
+ }
712
+
713
+ if (args.text && args.text.value !== '') {
714
+ const text = await one(TEXT_FIELD, args.text.value, args.text.format)
715
+ if (!text.ok) return unfinished(TEXT_FIELD, text)
716
+ heads[TEXT_FIELD] = text.id
717
+ }
718
+
719
+ const others = args.others ?? []
720
+ const type = BASE_TYPE_OF_KIND[root.kind]
721
+ if (others.length > 1 && type && args.inOrder.includes(type)) {
722
+ let together: WriteChangeResult
723
+ try {
724
+ together = await writeChanges({
725
+ ...common,
726
+ inOrder: args.inOrder,
727
+ fields: others.map((o) => ({ field: o.field, value: o.value, prev: root.id })),
728
+ build: (input) => args.build(input),
729
+ })
730
+ } catch (error) {
731
+ together = { ok: false, refused: error instanceof Error ? error.message : String(error) }
732
+ }
733
+ if (!together.ok) return unfinished(others.map((o) => o.field).join(', '), together)
734
+ for (const o of others) heads[o.field] = together.id
735
+ } else {
736
+ for (const o of others) {
737
+ const written = await one(o.field, o.value)
738
+ if (!written.ok) return unfinished(o.field, written)
739
+ heads[o.field] = written.id
740
+ }
741
+ }
742
+ return { ok: true, root, address, heads }
743
+ }
package/src/index.ts CHANGED
@@ -106,6 +106,7 @@ export {
106
106
  type FolderRecord,
107
107
  type ResolvedSlot,
108
108
  type ResolvedAction,
109
+ type ResolvedOption,
109
110
  type ActionFormField,
110
111
  type ProseFormat,
111
112
  type ManifestAction,
@@ -274,6 +275,10 @@ export {
274
275
  combineChanges,
275
276
  writeChange,
276
277
  writeChanges,
278
+ DELETED_FIELD,
279
+ setDeleted,
280
+ createFile,
281
+ finishCreating,
277
282
  type CurrentField,
278
283
  type FileFields,
279
284
  type Conflict,
@@ -281,6 +286,10 @@ export {
281
286
  type WriteChangeArgs,
282
287
  type WriteChangesArgs,
283
288
  type WriteChangeResult,
289
+ type WriteChangeFailure,
290
+ type SetDeletedArgs,
291
+ type CreateFileArgs,
292
+ type CreateFileResult,
284
293
  } from './fields.js'
285
294
 
286
295
  /**
package/src/projection.ts CHANGED
@@ -890,7 +890,26 @@ export interface ActionFormField {
890
890
  */
891
891
  format?: ProseFormat
892
892
  /** When the property names a vocabulary, its entries, already looked up. */
893
- options?: { value: string; label: string; colour?: string }[]
893
+ options?: ResolvedOption[]
894
+ }
895
+
896
+ /**
897
+ * A vocabulary entry a consumer draws and writes from. `stage` is the entry's
898
+ * declared stage when it is one of the four (SPEC §7.3) — what an app that
899
+ * builds its own change passes to {@link stageTagFor}, so the change says what
900
+ * the choice means as a declared action's does (EAC-5).
901
+ */
902
+ export interface ResolvedOption {
903
+ value: string
904
+ label: string
905
+ colour?: string
906
+ stage?: Stage
907
+ }
908
+
909
+ /** A vocabulary entry as a consumer gets it: its stage only when it is one of the four. */
910
+ function resolvedOption(entry: { value: string; label: string; colour: string; stage?: string }): ResolvedOption {
911
+ const stage = asStage(entry.stage)
912
+ return { value: entry.value, label: entry.label, colour: entry.colour, ...(stage ? { stage } : {}) }
894
913
  }
895
914
 
896
915
  /**
@@ -923,8 +942,8 @@ export interface ResolvedAction {
923
942
  * it.
924
943
  */
925
944
  control: 'select' | 'pubkey' | 'text' | 'form' | 'confirm'
926
- /** For `select`: the declared vocabulary, already looked up. */
927
- options?: { value: string; label: string; colour?: string }[]
945
+ /** For `select`: the declared vocabulary, already looked up, each entry with its stage (see {@link ResolvedOption}). */
946
+ options?: ResolvedOption[]
928
947
  /**
929
948
  * For `form`: the fields to draw, in declaration order, with any vocabulary
930
949
  * already looked up — the same service `options` performs for a `select`.
@@ -1126,13 +1145,7 @@ function resolveActions(
1126
1145
  // Prose only where the value is `content` — a tag is a scalar (§7.3).
1127
1146
  ...(spec.target === 'content' && proseFormatOf(spec.format) ? { format: proseFormatOf(spec.format) } : {}),
1128
1147
  ...(spec.enum && manifest.vocabularies?.[spec.enum]
1129
- ? {
1130
- options: manifest.vocabularies[spec.enum].map((v) => ({
1131
- value: v.value,
1132
- label: v.label,
1133
- colour: v.colour,
1134
- })),
1135
- }
1148
+ ? { options: manifest.vocabularies[spec.enum].map(resolvedOption) }
1136
1149
  : {}),
1137
1150
  })),
1138
1151
  // The parent is not a property and never appears in `properties`; it
@@ -1156,7 +1169,7 @@ function resolveActions(
1156
1169
  ...(action.effect ? { effect: action.effect } : {}),
1157
1170
  control,
1158
1171
  ...(format ? { format } : {}),
1159
- options: vocab?.map((v) => ({ value: v.value, label: v.label, colour: v.colour })),
1172
+ options: vocab?.map(resolvedOption),
1160
1173
  current: action.emits.field ? folded[action.emits.field]?.value : undefined,
1161
1174
  field: action.emits.field,
1162
1175
  })