@estiva-app/interop 0.34.0 → 0.36.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
@@ -15,6 +15,14 @@
15
15
  import { decodeNaddr, decodeNevent, encodeNaddr, encodeNevent, findNaddrs, pointerToAddress, referenceToPointer, type AddressPointer, type EventPointer } from '@estiva-app/protocol'
16
16
  import { imetaOf, parseProfile, type Imeta, type Profile, type SignedEvent } from '@estiva-app/protocol'
17
17
  import { MAX_FILTERS_PER_QUERY, RELAY_PAGE_CEILING } from '@estiva-app/protocol'
18
+ import {
19
+ attachmentsInDocument,
20
+ BLOCK_DOCUMENT_FORMAT,
21
+ CONTENT_FORMAT_TAG,
22
+ imetaTag,
23
+ parseBlockDocument,
24
+ } from '@estiva-app/protocol'
25
+ import { planPlaceFile, planUnlistFile, type FolderRef } from './folders.js'
18
26
 
19
27
  /** Query the relay. Returns matching events; shape mirrors the HTTP bridge. */
20
28
  export type QueryFn = (filters: Record<string, unknown>[]) => Promise<SignedEvent[]>
@@ -429,6 +437,97 @@ export async function conversationsOf(
429
437
  return conversations
430
438
  }
431
439
 
440
+ /** Every thread of one file's conversation, keyed by the comment it hangs from. */
441
+ export interface Threads {
442
+ /** The root comments themselves, by id — the only read that reports their `kind` and tags. */
443
+ roots: Record<string, SignedEvent>
444
+ /** Direct replies to each root, oldest first. A root with none is absent, not `[]`. */
445
+ replies: Record<string, SignedEvent[]>
446
+ }
447
+
448
+ /**
449
+ * The replies under a file's comments — {@link conversationsOf}'s counterpart,
450
+ * read by `#e` (PRO-20, from Peek's FOL-19 thread pane).
451
+ *
452
+ * **Asked by `#e`, not by `#a`, and that is the whole reason this exists.** A
453
+ * reply's lowercase tags name its parent comment, not the file (SPEC §6.4), so
454
+ * the `#a` read that brings the roots never brings a reply — whichever app
455
+ * wrote it. `rootIds` are those roots, typically `conversationsOf`'s ids.
456
+ *
457
+ * **Every thread in one request.** The roots by `ids` and their replies by
458
+ * `#e` go in one POST, because a `#e` filter takes a list: a whole pane's
459
+ * replies cost the round trip of one thread's, which is what lets a comment
460
+ * carry an honest reply count. The roots come back beside them because NIP-22's
461
+ * lowercase `k` on a reply names the *parent's* kind, and no projection reports
462
+ * it.
463
+ *
464
+ * The kinds are the owning app's, from its manifest (`commentKindsOf`), so a
465
+ * NIP-22 `kind:1111` reply and Ship's `kind:9` ones both arrive. No manifest,
466
+ * or a reference that does not decode, answers empty rather than guessing 1111.
467
+ *
468
+ * Only *direct* replies: a reply's lowercase `e` names its immediate parent, so
469
+ * a reply to a reply hangs off that reply and is not here. The replies share
470
+ * one `limit`, by default `CONVERSATION_LIMIT` — the same budget as one file's
471
+ * comment read, and what Peek's pane asks for.
472
+ *
473
+ * A refused read is whatever `query` does with one — this adds no catch, so an
474
+ * unreadable thread and an unanswered one stay distinguishable.
475
+ */
476
+ export async function threadsOf(
477
+ /** The file's address, or any reference `referenceToPointer` reads. */
478
+ reference: string,
479
+ rootIds: readonly string[],
480
+ query: QueryFn,
481
+ cache?: ProjectionCache,
482
+ /** How many replies, across every thread, one read asks for. */
483
+ limit: number = CONVERSATION_LIMIT,
484
+ ): Promise<Threads> {
485
+ const empty: Threads = { roots: {}, replies: {} }
486
+ if (rootIds.length === 0) return empty
487
+ let pointer: AddressPointer
488
+ try {
489
+ pointer = referenceToPointer(reference)
490
+ } catch {
491
+ return empty
492
+ }
493
+ const resolved = await resolveManifest(pointer, query, cache)
494
+ if (!resolved) return empty
495
+ const kinds = commentKindsOf(resolved.manifest)
496
+
497
+ const ids = [...new Set(rootIds)]
498
+ const events = await query([
499
+ { ids, limit: ids.length },
500
+ { kinds, '#e': ids, limit },
501
+ ])
502
+ const wanted = new Set(ids)
503
+ const roots: Record<string, SignedEvent> = {}
504
+ const replies: Record<string, SignedEvent[]> = {}
505
+ const seen = new Set<string>()
506
+ for (const event of events) {
507
+ if (seen.has(event.id)) continue
508
+ seen.add(event.id)
509
+ if (wanted.has(event.id)) {
510
+ roots[event.id] = event
511
+ continue
512
+ }
513
+ /*
514
+ The parent. A NIP-10 `reply` marker says it outright, and then only that
515
+ one counts: a reply to a reply also carries the thread's `root`-marked
516
+ `e`, which names a wanted id and is not its parent. Unmarked (NIP-22's
517
+ single lowercase `e`, or a bare mention beside it), the `e` naming a root
518
+ of *this* conversation — picking the first would file it under a quote.
519
+ */
520
+ const es = event.tags.filter((tag) => tag[0] === 'e' && tag[1])
521
+ const parent = (es.find((tag) => tag[3] === 'reply') ?? es.find((tag) => wanted.has(tag[1])))?.[1]
522
+ if (parent && wanted.has(parent)) (replies[parent] ??= []).push(event)
523
+ }
524
+ // Oldest first, ties by id so two replies in one second never swap places.
525
+ for (const thread of Object.values(replies)) {
526
+ thread.sort((a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : 1))
527
+ }
528
+ return { roots, replies }
529
+ }
530
+
432
531
  /**
433
532
  * How many targets a reaction read asks about — SPEC §6.6, decided by CON-1.
434
533
  *
@@ -742,6 +841,17 @@ interface SlotSpec {
742
841
  * written before this reading exactly as it did.
743
842
  */
744
843
  match?: 'address' | 'identifier'
844
+ /**
845
+ * The field on the child whose change moves it to another parent — SPEC
846
+ * §7.2, MAN-1. `project` on Ship's issues, `parent` on a bare file.
847
+ *
848
+ * The `via` tag is written once, by the child's author, on a root only
849
+ * they may replace; a move is therefore a change event, and this names the
850
+ * field it sets. The folded value wins over the tag, and an empty one is a
851
+ * move to no parent. Ignored with `match: 'identifier'`, because a move's
852
+ * value is an address.
853
+ */
854
+ movedBy?: string
745
855
  }
746
856
  }
747
857
 
@@ -820,11 +930,38 @@ export interface ManifestAction {
820
930
  * published, this is what also gets fetched. See `commentKindsOf`.
821
931
  */
822
932
  alsoRead?: number[]
933
+ /**
934
+ * On a creation: the tag the new root names its Folder with — `h`, the
935
+ * default, or `buzz-channel` (SPEC §7.3, MAN-1).
936
+ *
937
+ * `buzz-channel` is how a Ship project is written: the relay stores the
938
+ * record globally, so anybody can discover the project, while its changes
939
+ * and comments keep `h`. Any other value is refused when building, because
940
+ * a Folder named in a tag nothing reads is no Folder.
941
+ */
942
+ placement?: string
943
+ /**
944
+ * That objects this action writes are named in their Folder's state, so a
945
+ * creation is followed by a `kind:1852` add and a deletion by a remove from
946
+ * each Folder listing it (SPEC §7.3, MAN-1; FOL-48).
947
+ *
948
+ * Only {@link buildActionEvents} builds one, because only its caller can
949
+ * say whether a Folder has state — a read, never a guess.
950
+ */
951
+ listed?: boolean
823
952
  }
824
953
  input?: {
825
954
  type: string
826
955
  /** For a scalar input: the vocabulary its value must come from. */
827
956
  enum?: string
957
+ /**
958
+ * For a scalar change: the richest content model the owner accepts for the
959
+ * value — SPEC §7.3's `format`, MAN-1. `estiva-blocks-1` is a block
960
+ * document (§13.3). A format on the declaration, not a new type, because
961
+ * the wire value is a string either way; a plain value is still accepted,
962
+ * written untagged as marker text (§13.4).
963
+ */
964
+ format?: string
828
965
  /**
829
966
  * For `type: 'object'`: the fields a consumer draws, and which are required.
830
967
  *
@@ -844,8 +981,12 @@ export interface ManifestAction {
844
981
  * At most one property may do it. Two would be two writers of one field,
845
982
  * and the second silently winning is exactly the shape of bug this
846
983
  * vocabulary exists to make impossible.
984
+ *
985
+ * **A property targeting `content` may declare a `format`** — MAN-1, the
986
+ * same field a scalar input declares. Meaningless on a property written to
987
+ * a tag, which is a scalar, and ignored there.
847
988
  */
848
- properties?: Record<string, { type?: string; enum?: string; target?: 'content' }>
989
+ properties?: Record<string, { type?: string; enum?: string; target?: 'content'; format?: string }>
849
990
  required?: string[]
850
991
  }
851
992
  }
@@ -874,10 +1015,31 @@ export interface ActionFormField {
874
1015
  * have to, and one that ignores it still publishes the right event.
875
1016
  */
876
1017
  target?: 'content'
1018
+ /**
1019
+ * That the field is prose the owner accepts as a block document — MAN-1.
1020
+ *
1021
+ * Set only for a content field declaring a format this version writes, so a
1022
+ * consumer that sees it may draw a block editor and pass
1023
+ * `contentFormat: 'estiva-blocks-1'` to {@link buildActionEvent}. A consumer
1024
+ * that draws a text box instead still publishes a correct event (§7.3).
1025
+ */
1026
+ format?: ProseFormat
877
1027
  /** When the property names a vocabulary, its entries, already looked up. */
878
1028
  options?: { value: string; label: string; colour?: string }[]
879
1029
  }
880
1030
 
1031
+ /**
1032
+ * The content formats a declaration may name and this version writes — only
1033
+ * SPEC §13.3's block document. An unknown format is not surfaced, so no
1034
+ * consumer draws an editor for a model nothing here can tag correctly.
1035
+ */
1036
+ export type ProseFormat = typeof BLOCK_DOCUMENT_FORMAT
1037
+
1038
+ /** The declared format, when it is one this version writes. */
1039
+ function proseFormatOf(declared: unknown): ProseFormat | undefined {
1040
+ return declared === BLOCK_DOCUMENT_FORMAT ? BLOCK_DOCUMENT_FORMAT : undefined
1041
+ }
1042
+
881
1043
  export interface ResolvedAction {
882
1044
  id: string
883
1045
  label: string
@@ -912,6 +1074,18 @@ export interface ResolvedAction {
912
1074
  * properties would publish an orphan.
913
1075
  */
914
1076
  createsUnder?: string
1077
+ /**
1078
+ * For a `text` change: that the value is prose the owner accepts as a block
1079
+ * document (MAN-1). See {@link ActionFormField.format} — the same rule for a
1080
+ * field of a form.
1081
+ */
1082
+ format?: ProseFormat
1083
+ /**
1084
+ * That building this action needs to know the Folder's state: whether it has
1085
+ * any, for a creation, or which Folders name the object, for a deletion
1086
+ * (`emits.listed`, MAN-1). Pass it to {@link buildActionEvents}.
1087
+ */
1088
+ listed?: true
915
1089
  /** The value this field holds right now, so a control can show it. */
916
1090
  current?: string
917
1091
  field?: string
@@ -971,7 +1145,7 @@ function resolveActions(
971
1145
  */
972
1146
  const isChange = !!action.emits.field
973
1147
  const isComment = action.emits.scope === 'address'
974
- const isCreation = action.input?.type === 'object' && !!action.input.properties
1148
+ const isCreation = isCreationAction(action)
975
1149
  // Four, since 0.25.0. Decided by the kind before the other three, so a
976
1150
  // manifest that put `scope: 'address'` on its deletion — the target *is*
977
1151
  // an address — is not mistaken for a comment.
@@ -985,6 +1159,7 @@ function resolveActions(
985
1159
  ...(action.description ? { description: action.description } : {}),
986
1160
  ...(action.effect ? { effect: action.effect } : {}),
987
1161
  control: 'confirm',
1162
+ ...(action.emits.listed === true ? { listed: true as const } : {}),
988
1163
  })
989
1164
  continue
990
1165
  }
@@ -1012,6 +1187,8 @@ function resolveActions(
1012
1187
  a one-line input and drawing prose.
1013
1188
  */
1014
1189
  ...(spec.target ? { target: spec.target } : {}),
1190
+ // Prose only where the value is `content` — a tag is a scalar (§7.3).
1191
+ ...(spec.target === 'content' && proseFormatOf(spec.format) ? { format: proseFormatOf(spec.format) } : {}),
1015
1192
  ...(spec.enum && manifest.vocabularies?.[spec.enum]
1016
1193
  ? {
1017
1194
  options: manifest.vocabularies[spec.enum].map((v) => ({
@@ -1026,17 +1203,23 @@ function resolveActions(
1026
1203
  // comes from `emits`, and a form that omitted it would publish an
1027
1204
  // orphan the owning app cannot show anywhere.
1028
1205
  ...(action.emits.toAddressOf ? { createsUnder: action.emits.toAddressOf } : {}),
1206
+ ...(action.emits.listed === true ? { listed: true as const } : {}),
1029
1207
  })
1030
1208
  continue
1031
1209
  }
1032
1210
 
1033
1211
  const vocab = action.input?.enum ? manifest.vocabularies?.[action.input.enum] : undefined
1212
+ const control = vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text'
1213
+ // A change only: a comment's body is §13.2 marker text, and a format on
1214
+ // one is nothing this version writes (`buildActionEvent` refuses it).
1215
+ const format = control === 'text' && isChange ? proseFormatOf(action.input?.format) : undefined
1034
1216
  out.push({
1035
1217
  id: action.id,
1036
1218
  label: action.label,
1037
1219
  ...(action.description ? { description: action.description } : {}),
1038
1220
  ...(action.effect ? { effect: action.effect } : {}),
1039
- control: vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text',
1221
+ control,
1222
+ ...(format ? { format } : {}),
1040
1223
  options: vocab?.map((v) => ({ value: v.value, label: v.label, colour: v.colour })),
1041
1224
  current: action.emits.field ? folded[action.emits.field]?.value : undefined,
1042
1225
  field: action.emits.field,
@@ -1308,9 +1491,6 @@ export const KIND_BARE_FILE = 30840
1308
1491
  */
1309
1492
  export const BARE_FILE_MANIFEST_ADDRESS = 'spec:6.7'
1310
1493
 
1311
- /** The field a bare file's `kind:1851` re-parent sets (SPEC §6.7). */
1312
- const BARE_FILE_PARENT_FIELD = 'parent'
1313
-
1314
1494
  const BARE_FILE_MANIFEST: Manifest = {
1315
1495
  name: 'File',
1316
1496
  about: 'A file no app owns. Its conversation is what every file has; its type adds nothing.',
@@ -1333,7 +1513,11 @@ const BARE_FILE_MANIFEST: Manifest = {
1333
1513
  // of *other* kinds are found the other way round, by their own `a`
1334
1514
  // (`parentRefOf` below), which is FOL-4's generic direction; this slot
1335
1515
  // is the one the existing `list` machinery can draw today.
1336
- list: { children: { kind: KIND_BARE_FILE, via: 'a', limit: 200 } },
1516
+ //
1517
+ // `movedBy` is SPEC §6.7's `parent` field, declared rather than
1518
+ // hard-coded since MAN-1, so a bare file moves by the rule every other
1519
+ // kind does — the move action below sets the same field.
1520
+ list: { children: { kind: KIND_BARE_FILE, via: 'a', limit: 200, movedBy: 'parent' } },
1337
1521
  },
1338
1522
  },
1339
1523
  /*
@@ -1407,7 +1591,7 @@ const BARE_FILE_MANIFEST: Manifest = {
1407
1591
  'the team may; who can read the file does not change.',
1408
1592
  effect: 'writes',
1409
1593
  appliesTo: [String(KIND_BARE_FILE)],
1410
- emits: { kind: 1851, field: BARE_FILE_PARENT_FIELD },
1594
+ emits: { kind: 1851, field: 'parent' },
1411
1595
  input: { type: 'string' },
1412
1596
  },
1413
1597
  {
@@ -2025,6 +2209,48 @@ export function actionProblems(declared: unknown): string[] {
2025
2209
  }
2026
2210
  }
2027
2211
 
2212
+ /*
2213
+ MAN-1's three declarations, each of which fails quietly on the consumer's
2214
+ side: an unknown placement or format is refused or ignored at the button,
2215
+ and a `listed` on a change is simply never acted on.
2216
+ */
2217
+ const emits = (action as { emits?: { kind?: unknown; field?: unknown; placement?: unknown; listed?: unknown } }).emits
2218
+ const input = (action as { input?: { type?: unknown; format?: unknown } }).input
2219
+ const creates = input?.type === 'object' && !!properties
2220
+ if (emits?.placement !== undefined && !(creates && PLACEMENTS.includes(emits.placement as string))) {
2221
+ problems.push(
2222
+ creates
2223
+ ? `${name} places its object with ${JSON.stringify(emits.placement)}, and a Folder is named by ${PLACEMENTS.join(' or ')} — a consumer refuses the action.`
2224
+ : `${name} declares a placement and creates nothing; only a new root names its Folder, so it is ignored.`,
2225
+ )
2226
+ }
2227
+ if (emits?.listed !== undefined && emits.listed !== true) {
2228
+ problems.push(`${name} declares listed ${JSON.stringify(emits.listed)}; the only value is true.`)
2229
+ } else if (emits?.listed === true && !creates && emits.kind !== KIND_DELETION) {
2230
+ problems.push(`${name} declares listed on an action that neither creates nor deletes, so no Folder command follows it.`)
2231
+ }
2232
+ const formats: [string, unknown, boolean][] = [
2233
+ // A scalar format means something on a change only: a comment's body is
2234
+ // marker text, and a deletion takes no value.
2235
+ ...(input?.format !== undefined
2236
+ ? [['its input', input.format, !creates && !!emits?.field && emits.kind !== KIND_DELETION] as [string, unknown, boolean]]
2237
+ : []),
2238
+ ...Object.entries(properties && typeof properties === 'object' ? properties : {})
2239
+ .filter(([, spec]) => (spec as { format?: unknown } | null)?.format !== undefined)
2240
+ .map(([property, spec]): [string, unknown, boolean] => [
2241
+ `"${property}"`,
2242
+ (spec as { format?: unknown }).format,
2243
+ (spec as { target?: unknown }).target === 'content',
2244
+ ]),
2245
+ ]
2246
+ for (const [where, format, applies] of formats) {
2247
+ if (!applies) {
2248
+ problems.push(`${name} declares a format on ${where}, which is neither a creation's content nor a change's value, so it is ignored.`)
2249
+ } else if (!proseFormatOf(format)) {
2250
+ problems.push(`${name} declares format ${JSON.stringify(format)} on ${where}, and the only format is ${BLOCK_DOCUMENT_FORMAT}. A consumer draws it as plain text.`)
2251
+ }
2252
+ }
2253
+
2028
2254
  return problems
2029
2255
  }
2030
2256
 
@@ -2363,8 +2589,10 @@ export interface ForeignObject {
2363
2589
  */
2364
2590
  parentRef?: string
2365
2591
  /**
2366
- * The folded field that re-parents this object, when there is one — `parent`
2367
- * on a bare file (SPEC §6.7), absent for every other kind today (FOL-4).
2592
+ * The folded field that re-parents this object, when its owner declares one
2593
+ * — SPEC §7.2's `movedBy`: `parent` on a bare file (§6.7), `project` on an
2594
+ * issue whose app declares it (MAN-1). Hard-coded to the bare file before
2595
+ * 0.36.0.
2368
2596
  *
2369
2597
  * **For a consumer that draws field-setting actions as property rows.** The
2370
2598
  * action setting this field is a move, and its value is an address: drawn as
@@ -2373,6 +2601,14 @@ export interface ForeignObject {
2373
2601
  * title's rename takes, matched on the field for the same reason.
2374
2602
  */
2375
2603
  parentField?: string
2604
+ /**
2605
+ * The kind a move may name — the kind whose projection declares the
2606
+ * `movedBy` (MAN-1): `30850` for a Ship issue, so a move control offers
2607
+ * projects and not other issues. Absent with `parentField` on a bare file,
2608
+ * which may sit under any kind (§6.7). {@link nestingOf}'s `moveTargetsOf`
2609
+ * reads it.
2610
+ */
2611
+ parentKind?: number
2376
2612
  kind: number
2377
2613
  /**
2378
2614
  * The layout hint the owner declared — **a type or an ordered chain of them.**
@@ -2501,7 +2737,7 @@ function buildObject(args: {
2501
2737
  comments: args.comments ?? [],
2502
2738
  listsChildren: listsChildrenOf(projection, manifest),
2503
2739
  parentRef: parentRefOf(manifest, pointer.kind, root, folded),
2504
- ...(pointer.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
2740
+ ...parentFieldsOf(manifest, pointer.kind),
2505
2741
  folder: tagValue(root, 'h'),
2506
2742
  // Substituted here rather than in the component: `<bech32>` is a NIP-89
2507
2743
  // detail, and the widget's job is to draw a link, not to know the spec.
@@ -2982,7 +3218,7 @@ function withPeople({ object, children }: AssembledObject, people: People): Fore
2982
3218
  */
2983
3219
  function declaredChildSpec(projection: {
2984
3220
  slots: Record<string, SlotSpec | SlotSpec[]>
2985
- }): { kind: number; via: string; limit?: number; match?: string } | undefined {
3221
+ }): { kind: number; via: string; limit?: number; match?: string; movedBy?: string } | undefined {
2986
3222
  const spec = projection.slots.list
2987
3223
  return !Array.isArray(spec) ? spec?.children : undefined
2988
3224
  }
@@ -3017,15 +3253,24 @@ function parentRefOf(
3017
3253
  direction lets Ship's project list its issues without an issue knowing what
3018
3254
  a project is; this one lets a topic sit under a project, an issue, or a kind
3019
3255
  nobody has met, without that kind's owner declaring bare files as children.
3020
- Re-parenting is a `parent` change event, seeded by the root tag, the way an
3021
- issue's `project` field works (SPEC §6.7).
3256
+ Re-parenting is a change to the declared `movedBy` field, seeded by the
3257
+ root tag — `parent` on a bare file, `project` on a Ship issue (SPEC §7.2).
3022
3258
  */
3023
- if (kind === KIND_BARE_FILE) {
3259
+ const movedBy = movedByOf(manifest, kind)
3260
+ if (movedBy) {
3024
3261
  // A folded empty value is a move to the top, not an absence: falling back
3025
3262
  // to the root tag would put the file straight back under the parent it
3026
3263
  // was moved out of (FOL-4).
3027
- const moved = folded[BARE_FILE_PARENT_FIELD]
3028
- if (moved) return moved.value || undefined
3264
+ // A value that is not an address of the declared parent kind names nothing
3265
+ // this object can sit under, so it is a move to nowhere rather than a ref a
3266
+ // consumer might try to fetch.
3267
+ const moved = folded[movedBy.field]
3268
+ if (moved) {
3269
+ const prefix = movedBy.parentKind === undefined ? /^\d+:[0-9a-f]{64}:/ : new RegExp(`^${movedBy.parentKind}:[0-9a-f]{64}:`)
3270
+ return prefix.test(moved.value) ? moved.value : undefined
3271
+ }
3272
+ }
3273
+ if (kind === KIND_BARE_FILE) {
3029
3274
  return root.tags.find((t) => t[0] === 'a' && t[1] && /^\d+:[0-9a-f]{64}:/.test(t[1]))?.[1]
3030
3275
  }
3031
3276
  for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
@@ -3046,6 +3291,34 @@ function parentRefOf(
3046
3291
  return undefined
3047
3292
  }
3048
3293
 
3294
+ /**
3295
+ * The field that moves a `kind` object to another parent, and the kind of
3296
+ * parent it names — SPEC §7.2's `movedBy`, read off whichever projection lists
3297
+ * `kind` as its children (MAN-1).
3298
+ *
3299
+ * `parentKind` is absent for a bare file: §6.7 lets one sit under a file of any
3300
+ * kind, so its own list naming bare files is not a limit on where it may go.
3301
+ * Absent too for `match: 'identifier'`, where `movedBy` is ignored because a
3302
+ * move's value is an address and that list compares identifiers.
3303
+ */
3304
+ function movedByOf(manifest: Manifest, kind: number): { field: string; parentKind?: number } | undefined {
3305
+ for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
3306
+ const children = declaredChildSpec(projection as { slots: Record<string, SlotSpec | SlotSpec[]> })
3307
+ if (!children || children.kind !== kind || !children.movedBy || children.match === 'identifier') continue
3308
+ return kind === KIND_BARE_FILE ? { field: children.movedBy } : { field: children.movedBy, parentKind: Number(parentKind) }
3309
+ }
3310
+ return undefined
3311
+ }
3312
+
3313
+ /** {@link movedByOf} as the two `ForeignObject` fields, both builders' shape. */
3314
+ function parentFieldsOf(manifest: Manifest, kind: number): { parentField?: string; parentKind?: number } {
3315
+ const moved = movedByOf(manifest, kind)
3316
+ if (!moved) return {}
3317
+ return moved.parentKind === undefined
3318
+ ? { parentField: moved.field }
3319
+ : { parentField: moved.field, parentKind: moved.parentKind }
3320
+ }
3321
+
3049
3322
  /** Both halves of the question a disclosure control asks. */
3050
3323
  function listsChildrenOf(
3051
3324
  projection: { slots: Record<string, SlotSpec | SlotSpec[]> },
@@ -3179,7 +3452,7 @@ function buildChildObject(args: {
3179
3452
  // an inconsistent shape is what makes a consumer defensive about a value it
3180
3453
  // should be able to trust.
3181
3454
  parentRef: parentRefOf(manifest, root.kind, root),
3182
- ...(root.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
3455
+ ...parentFieldsOf(manifest, root.kind),
3183
3456
  folder: tagValue(root, 'h'),
3184
3457
  /*
3185
3458
  `<bech32>` is whichever form this object actually has.
@@ -3819,6 +4092,51 @@ export async function resolveFolderProject(
3819
4092
  */
3820
4093
  const isAddressableKind = (kind: number) => kind >= 30000 && kind < 40000
3821
4094
 
4095
+ /**
4096
+ * The tags a new root may name its Folder with — SPEC §7.3's `placement`.
4097
+ *
4098
+ * The two a relay indexes for a Folder's containment read and {@link folderOf}
4099
+ * reads. Closed, because a root placed in any other tag belongs to no Folder
4100
+ * and nothing would say so.
4101
+ */
4102
+ const PLACEMENTS: readonly string[] = ['h', 'buzz-channel']
4103
+
4104
+ /**
4105
+ * The tags a prose value carries — SPEC §7.3's `format`, MAN-1.
4106
+ *
4107
+ * **Tagged only when the caller says the value is in the declared format**, and
4108
+ * then checked, because a reader decides the model by the tag alone (§13.4): a
4109
+ * `content-format` on marker text renders nothing, and one on a document the
4110
+ * relay cannot parse renders JSON at a person. Without `contentFormat` the value
4111
+ * is marker text and carries nothing, which every reader must accept — so a
4112
+ * consumer that draws a text box for a prose field still publishes correctly.
4113
+ *
4114
+ * A document's attachments are named again as `imeta`, which §13.3 requires of
4115
+ * every event holding one and which ingest verifies against stored blobs.
4116
+ */
4117
+ function proseTags(args: {
4118
+ label: string
4119
+ declared: string | undefined
4120
+ contentFormat: string | undefined
4121
+ value: string
4122
+ }): string[][] | string {
4123
+ const { label, declared, contentFormat, value } = args
4124
+ if (contentFormat === undefined) return []
4125
+ if (proseFormatOf(declared) !== contentFormat) {
4126
+ return proseFormatOf(declared)
4127
+ ? `"${label}" takes ${proseFormatOf(declared)}, not ${contentFormat}.`
4128
+ : `"${label}" declares no ${contentFormat} value, so it is written as plain text.`
4129
+ }
4130
+ // Clearing a field is not a document; an empty value says nothing to tag.
4131
+ if (value === '') return []
4132
+ try {
4133
+ parseBlockDocument(value)
4134
+ } catch (e) {
4135
+ return `"${label}" was handed ${contentFormat} that is ${(e as Error).message}.`
4136
+ }
4137
+ return [[CONTENT_FORMAT_TAG, contentFormat], ...attachmentsInDocument(value, contentFormat).map(imetaTag)]
4138
+ }
4139
+
3822
4140
  /**
3823
4141
  * The event an object-creating action publishes.
3824
4142
  *
@@ -3838,6 +4156,7 @@ function buildCreationEvent(args: {
3838
4156
  folder: string
3839
4157
  value: string | Record<string, string>
3840
4158
  newId?: string
4159
+ contentFormat?: string
3841
4160
  pubkey: string
3842
4161
  createdAtMs: number
3843
4162
  }): UnsignedActionEvent | string {
@@ -3891,6 +4210,20 @@ function buildCreationEvent(args: {
3891
4210
  }
3892
4211
  const bodyField = bodyFields[0]
3893
4212
 
4213
+ const placement = declared.emits.placement ?? 'h'
4214
+ if (!PLACEMENTS.includes(placement)) {
4215
+ return `"${declared.label}" places its object with "${placement}", and a Folder is named by ${PLACEMENTS.join(' or ')}.`
4216
+ }
4217
+
4218
+ // Only the content field can be prose, so only its value is ever tagged.
4219
+ const prose = proseTags({
4220
+ label: declared.label,
4221
+ declared: bodyField ? properties[bodyField]?.format : undefined,
4222
+ contentFormat: args.contentFormat,
4223
+ value: bodyField ? (value[bodyField] ?? '') : '',
4224
+ })
4225
+ if (typeof prose === 'string') return prose
4226
+
3894
4227
  const tags: string[][] = []
3895
4228
  if (isAddressableKind(declared.emits.kind)) tags.push(['d', newId!])
3896
4229
  // A property's name is the tag it writes, unless it declared `content`. See
@@ -3904,7 +4237,7 @@ function buildCreationEvent(args: {
3904
4237
  if (declared.emits.setTag && declared.emits.toAddressOf === 'self') {
3905
4238
  tags.push([declared.emits.setTag, address])
3906
4239
  }
3907
- tags.push(['h', folder])
4240
+ tags.push([placement, folder], ...prose)
3908
4241
 
3909
4242
  return {
3910
4243
  pubkey: args.pubkey,
@@ -3915,7 +4248,8 @@ function buildCreationEvent(args: {
3915
4248
  }
3916
4249
  }
3917
4250
 
3918
- export function buildActionEvent(args: {
4251
+ /** What {@link buildActionEvent} and {@link buildActionEvents} are handed. */
4252
+ export interface ActionEventArgs {
3919
4253
  manifest: { records?: RecordsRule; actions?: ManifestAction[]; vocabularies?: Manifest['vocabularies'] }
3920
4254
  kind: number
3921
4255
  /** Address of the object being acted on. */
@@ -3938,10 +4272,110 @@ export function buildActionEvent(args: {
3938
4272
  * a pure function of its inputs, which is what lets a test assert on one.
3939
4273
  */
3940
4274
  newId?: string
4275
+ /**
4276
+ * The comment being answered, when this comment is a reply (PRO-20).
4277
+ *
4278
+ * SPEC §6.4's table: the uppercase `A`/`K`/`P` still name the file, and the
4279
+ * lowercase trio names this comment — its id, its kind and its author —
4280
+ * instead of repeating the file. So a reply carries no lowercase `a` and is
4281
+ * absent from the file's `#a` read; {@link threadsOf} is the read that finds
4282
+ * it. `kind` is the parent's own, which for one of Ship's replies is `9`.
4283
+ *
4284
+ * Refused on any action that is not a comment: nothing else has a parent.
4285
+ */
4286
+ replyTo?: { id: string; kind: number; author: string }
4287
+ /**
4288
+ * The format the action's prose value is in, when it is not marker text —
4289
+ * `'estiva-blocks-1'` for a block document (SPEC §7.3's `format`, MAN-1).
4290
+ *
4291
+ * The value of a scalar change, or of a creation's `content` field. Only a
4292
+ * format the action declares for that value is accepted, and the value is
4293
+ * parsed before it is tagged. Omitted, the value is written untagged as
4294
+ * marker text, which is always correct.
4295
+ */
4296
+ contentFormat?: string
3941
4297
  pubkey: string
3942
4298
  createdAtMs: number
3943
- }): UnsignedActionEvent | string {
3944
- const { manifest, kind, address, folder, actionId, value } = args
4299
+ }
4300
+
4301
+ /**
4302
+ * Build the event that performs a manifest-declared action — one event.
4303
+ *
4304
+ * **Refuses an action declaring `emits.listed`**, which is more than one event
4305
+ * (SPEC §7.3): building the root alone would publish an object its Folder does
4306
+ * not show, and report success. {@link buildActionEvents} builds those.
4307
+ */
4308
+ export function buildActionEvent(args: ActionEventArgs): UnsignedActionEvent | string {
4309
+ const declared = args.manifest.actions?.find((a) => a.id === args.actionId)
4310
+ if (declared?.emits.listed === true && (declared.emits.kind === KIND_DELETION || isCreationAction(declared))) {
4311
+ return `"${declared.label}" is followed by a Folder command, so it is built with buildActionEvents.`
4312
+ }
4313
+ return buildOneActionEvent(args)
4314
+ }
4315
+
4316
+ /** An action that makes a new object rather than changing one — a form. */
4317
+ function isCreationAction(declared: ManifestAction): boolean {
4318
+ return declared.input?.type === 'object' && !!declared.input.properties
4319
+ }
4320
+
4321
+ /**
4322
+ * Every event an action publishes, **in publish order** — SPEC §7.3, MAN-1.
4323
+ *
4324
+ * The first is what {@link buildActionEvent} builds. An action declaring
4325
+ * `emits.listed` is followed by the Folder commands that keep its Folder's
4326
+ * listing true, planned by `planPlaceFile` / `planUnlistFile`:
4327
+ *
4328
+ * - a creation: `kind:1852 add` naming the new address in the Folder it was
4329
+ * placed in, when `folderHasState` — none when the Folder has no state, where
4330
+ * a command would hide everything else filed there;
4331
+ * - a deletion: `kind:1852 remove` from each of `listedIn` that has state.
4332
+ *
4333
+ * Both facts come from the caller's read of `kind:30890` and are required
4334
+ * rather than defaulted, because a guess here is silent loss. Publish in order
4335
+ * and stop at the first refusal: each event assumes the ones before it landed.
4336
+ */
4337
+ export function buildActionEvents(
4338
+ args: ActionEventArgs & {
4339
+ /** For a `listed` creation: whether the Folder has state — from a read. */
4340
+ folderHasState?: boolean
4341
+ /** For a `listed` deletion: every Folder that lists the object, with `hasState` — from a read. */
4342
+ listedIn?: readonly FolderRef[]
4343
+ },
4344
+ ): UnsignedActionEvent[] | string {
4345
+ const first = buildOneActionEvent(args)
4346
+ if (typeof first === 'string') return first
4347
+ const declared = args.manifest.actions!.find((a) => a.id === args.actionId)!
4348
+ if (declared.emits.listed !== true) return [first]
4349
+
4350
+ if (declared.emits.kind === KIND_DELETION) {
4351
+ if (!args.listedIn) return `"${declared.label}" unlists what it deletes, and needs the Folders that list it.`
4352
+ // One remove per Folder, however many reads it came back from.
4353
+ const folders = [...new Map(args.listedIn.map((listing) => [listing.id, listing])).values()]
4354
+ return [
4355
+ first,
4356
+ ...folders.flatMap((listing) =>
4357
+ planUnlistFile(args.pubkey, args.createdAtMs, { folder: listing.id, address: args.address, hasState: listing.hasState }),
4358
+ ),
4359
+ ]
4360
+ }
4361
+ if (isCreationAction(declared)) {
4362
+ if (args.folderHasState === undefined) {
4363
+ return `"${declared.label}" lists what it creates, and needs to know whether the Folder has state.`
4364
+ }
4365
+ // A listing names addresses, and an object with no `d` has none.
4366
+ const identifier = first.tags.find((t) => t[0] === 'd')?.[1]
4367
+ if (identifier === undefined) {
4368
+ return `"${declared.label}" lists what it creates, and a kind ${first.kind} has no address to list.`
4369
+ }
4370
+ const created = pointerToAddress({ kind: first.kind, pubkey: first.pubkey, identifier, relays: [] })
4371
+ return [first, ...planPlaceFile(args.pubkey, args.createdAtMs, { folder: args.folder, address: created, hasState: args.folderHasState })]
4372
+ }
4373
+ // A change or a comment adds nothing to a Folder and removes nothing from it.
4374
+ return [first]
4375
+ }
4376
+
4377
+ function buildOneActionEvent(args: ActionEventArgs): UnsignedActionEvent | string {
4378
+ const { manifest, kind, address, folder, actionId, value, replyTo } = args
3945
4379
  const records = manifest.records
3946
4380
  const declared = manifest.actions?.find((a) => a.id === actionId)
3947
4381
  if (!declared) return `This app does not offer "${actionId}".`
@@ -3951,9 +4385,23 @@ export function buildActionEvent(args: {
3951
4385
  return `"${declared.label}" does not apply to a kind ${kind}.`
3952
4386
  }
3953
4387
 
4388
+ const isCreation = isCreationAction(declared)
4389
+
4390
+ // A reply is a comment with a parent — what the scalar path below builds for
4391
+ // an action that is neither a deletion nor a change. Refused here, before any
4392
+ // branch that would build something else and quietly drop the parent.
4393
+ if (replyTo && (isCreation || declared.emits.kind === KIND_DELETION || declared.emits.field)) {
4394
+ return `"${declared.label}" is not a comment, so it cannot reply to one.`
4395
+ }
4396
+ // Prose is a creation's content or a change's value (§7.3). A deletion has
4397
+ // no value, and a comment's body is §13.2 marker text.
4398
+ if (args.contentFormat !== undefined && !isCreation && (!declared.emits.field || declared.emits.kind === KIND_DELETION)) {
4399
+ return `"${declared.label}" takes no prose value, so it takes no content format.`
4400
+ }
4401
+
3954
4402
  // An object-creating action is a different event entirely — a new object
3955
4403
  // rather than a change to one — so it branches before the scalar path.
3956
- if (declared.input?.type === 'object' && declared.input.properties) {
4404
+ if (isCreation) {
3957
4405
  return buildCreationEvent({ ...args, declared, vocabularies: manifest.vocabularies })
3958
4406
  }
3959
4407
 
@@ -4017,24 +4465,42 @@ export function buildActionEvent(args: {
4017
4465
  }
4018
4466
  }
4019
4467
 
4468
+ // A prose value's `content-format` and `imeta` — a change only, per the
4469
+ // refusal above. Ship's order: the tag before `ts`, the files after it.
4470
+ const prose = declared.emits.field
4471
+ ? proseTags({ label: declared.label, declared: declared.input?.format, contentFormat: args.contentFormat, value })
4472
+ : []
4473
+ if (typeof prose === 'string') return prose
4474
+ const [formatTag, ...files] = prose
4475
+
4020
4476
  const tags: string[][] = declared.emits.field
4021
4477
  ? [
4022
4478
  [records.targetTag, address],
4023
4479
  [records.fieldTag, declared.emits.field],
4024
4480
  [records.valueTag, value],
4025
4481
  ['h', folder],
4482
+ ...(formatTag ? [formatTag] : []),
4026
4483
  ]
4027
4484
  : // NIP-22 comment. Built from the ratified NIP rather than from the
4028
4485
  // manifest, which is legitimate precisely because no app owns kind:1111 —
4029
4486
  // the same reason the owning app uses it. Uppercase tags name the thread
4030
- // root, lowercase the immediate parent.
4487
+ // root, lowercase the immediate parent: the file again for a top-level
4488
+ // comment, the comment answered for a reply (SPEC §6.4).
4031
4489
  [
4032
4490
  ['A', address],
4033
4491
  ['K', String(kind)],
4034
4492
  ['P', args.objectAuthor],
4035
- ['a', address],
4036
- ['k', String(kind)],
4037
- ['p', args.objectAuthor],
4493
+ ...(replyTo
4494
+ ? [
4495
+ ['e', replyTo.id],
4496
+ ['k', String(replyTo.kind)],
4497
+ ['p', replyTo.author],
4498
+ ]
4499
+ : [
4500
+ ['a', address],
4501
+ ['k', String(kind)],
4502
+ ['p', args.objectAuthor],
4503
+ ]),
4038
4504
  ['h', folder],
4039
4505
  ]
4040
4506
 
@@ -4043,6 +4509,7 @@ export function buildActionEvent(args: {
4043
4509
  // second would be separated by event id — arbitrarily, and differently
4044
4510
  // depending on which app you asked (FRICTION.md A6).
4045
4511
  if (records.order?.includes('ts')) tags.push(['ts', String(args.createdAtMs)])
4512
+ tags.push(...files)
4046
4513
 
4047
4514
  return {
4048
4515
  pubkey: args.pubkey,