@estiva-app/interop 0.35.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[]>
@@ -833,6 +841,17 @@ interface SlotSpec {
833
841
  * written before this reading exactly as it did.
834
842
  */
835
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
836
855
  }
837
856
  }
838
857
 
@@ -911,11 +930,38 @@ export interface ManifestAction {
911
930
  * published, this is what also gets fetched. See `commentKindsOf`.
912
931
  */
913
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
914
952
  }
915
953
  input?: {
916
954
  type: string
917
955
  /** For a scalar input: the vocabulary its value must come from. */
918
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
919
965
  /**
920
966
  * For `type: 'object'`: the fields a consumer draws, and which are required.
921
967
  *
@@ -935,8 +981,12 @@ export interface ManifestAction {
935
981
  * At most one property may do it. Two would be two writers of one field,
936
982
  * and the second silently winning is exactly the shape of bug this
937
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.
938
988
  */
939
- properties?: Record<string, { type?: string; enum?: string; target?: 'content' }>
989
+ properties?: Record<string, { type?: string; enum?: string; target?: 'content'; format?: string }>
940
990
  required?: string[]
941
991
  }
942
992
  }
@@ -965,10 +1015,31 @@ export interface ActionFormField {
965
1015
  * have to, and one that ignores it still publishes the right event.
966
1016
  */
967
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
968
1027
  /** When the property names a vocabulary, its entries, already looked up. */
969
1028
  options?: { value: string; label: string; colour?: string }[]
970
1029
  }
971
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
+
972
1043
  export interface ResolvedAction {
973
1044
  id: string
974
1045
  label: string
@@ -1003,6 +1074,18 @@ export interface ResolvedAction {
1003
1074
  * properties would publish an orphan.
1004
1075
  */
1005
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
1006
1089
  /** The value this field holds right now, so a control can show it. */
1007
1090
  current?: string
1008
1091
  field?: string
@@ -1062,7 +1145,7 @@ function resolveActions(
1062
1145
  */
1063
1146
  const isChange = !!action.emits.field
1064
1147
  const isComment = action.emits.scope === 'address'
1065
- const isCreation = action.input?.type === 'object' && !!action.input.properties
1148
+ const isCreation = isCreationAction(action)
1066
1149
  // Four, since 0.25.0. Decided by the kind before the other three, so a
1067
1150
  // manifest that put `scope: 'address'` on its deletion — the target *is*
1068
1151
  // an address — is not mistaken for a comment.
@@ -1076,6 +1159,7 @@ function resolveActions(
1076
1159
  ...(action.description ? { description: action.description } : {}),
1077
1160
  ...(action.effect ? { effect: action.effect } : {}),
1078
1161
  control: 'confirm',
1162
+ ...(action.emits.listed === true ? { listed: true as const } : {}),
1079
1163
  })
1080
1164
  continue
1081
1165
  }
@@ -1103,6 +1187,8 @@ function resolveActions(
1103
1187
  a one-line input and drawing prose.
1104
1188
  */
1105
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) } : {}),
1106
1192
  ...(spec.enum && manifest.vocabularies?.[spec.enum]
1107
1193
  ? {
1108
1194
  options: manifest.vocabularies[spec.enum].map((v) => ({
@@ -1117,17 +1203,23 @@ function resolveActions(
1117
1203
  // comes from `emits`, and a form that omitted it would publish an
1118
1204
  // orphan the owning app cannot show anywhere.
1119
1205
  ...(action.emits.toAddressOf ? { createsUnder: action.emits.toAddressOf } : {}),
1206
+ ...(action.emits.listed === true ? { listed: true as const } : {}),
1120
1207
  })
1121
1208
  continue
1122
1209
  }
1123
1210
 
1124
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
1125
1216
  out.push({
1126
1217
  id: action.id,
1127
1218
  label: action.label,
1128
1219
  ...(action.description ? { description: action.description } : {}),
1129
1220
  ...(action.effect ? { effect: action.effect } : {}),
1130
- control: vocab ? 'select' : action.input?.type === 'pubkey' ? 'pubkey' : 'text',
1221
+ control,
1222
+ ...(format ? { format } : {}),
1131
1223
  options: vocab?.map((v) => ({ value: v.value, label: v.label, colour: v.colour })),
1132
1224
  current: action.emits.field ? folded[action.emits.field]?.value : undefined,
1133
1225
  field: action.emits.field,
@@ -1399,9 +1491,6 @@ export const KIND_BARE_FILE = 30840
1399
1491
  */
1400
1492
  export const BARE_FILE_MANIFEST_ADDRESS = 'spec:6.7'
1401
1493
 
1402
- /** The field a bare file's `kind:1851` re-parent sets (SPEC §6.7). */
1403
- const BARE_FILE_PARENT_FIELD = 'parent'
1404
-
1405
1494
  const BARE_FILE_MANIFEST: Manifest = {
1406
1495
  name: 'File',
1407
1496
  about: 'A file no app owns. Its conversation is what every file has; its type adds nothing.',
@@ -1424,7 +1513,11 @@ const BARE_FILE_MANIFEST: Manifest = {
1424
1513
  // of *other* kinds are found the other way round, by their own `a`
1425
1514
  // (`parentRefOf` below), which is FOL-4's generic direction; this slot
1426
1515
  // is the one the existing `list` machinery can draw today.
1427
- 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' } },
1428
1521
  },
1429
1522
  },
1430
1523
  /*
@@ -1498,7 +1591,7 @@ const BARE_FILE_MANIFEST: Manifest = {
1498
1591
  'the team may; who can read the file does not change.',
1499
1592
  effect: 'writes',
1500
1593
  appliesTo: [String(KIND_BARE_FILE)],
1501
- emits: { kind: 1851, field: BARE_FILE_PARENT_FIELD },
1594
+ emits: { kind: 1851, field: 'parent' },
1502
1595
  input: { type: 'string' },
1503
1596
  },
1504
1597
  {
@@ -2116,6 +2209,48 @@ export function actionProblems(declared: unknown): string[] {
2116
2209
  }
2117
2210
  }
2118
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
+
2119
2254
  return problems
2120
2255
  }
2121
2256
 
@@ -2454,8 +2589,10 @@ export interface ForeignObject {
2454
2589
  */
2455
2590
  parentRef?: string
2456
2591
  /**
2457
- * The folded field that re-parents this object, when there is one — `parent`
2458
- * 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.
2459
2596
  *
2460
2597
  * **For a consumer that draws field-setting actions as property rows.** The
2461
2598
  * action setting this field is a move, and its value is an address: drawn as
@@ -2464,6 +2601,14 @@ export interface ForeignObject {
2464
2601
  * title's rename takes, matched on the field for the same reason.
2465
2602
  */
2466
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
2467
2612
  kind: number
2468
2613
  /**
2469
2614
  * The layout hint the owner declared — **a type or an ordered chain of them.**
@@ -2592,7 +2737,7 @@ function buildObject(args: {
2592
2737
  comments: args.comments ?? [],
2593
2738
  listsChildren: listsChildrenOf(projection, manifest),
2594
2739
  parentRef: parentRefOf(manifest, pointer.kind, root, folded),
2595
- ...(pointer.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
2740
+ ...parentFieldsOf(manifest, pointer.kind),
2596
2741
  folder: tagValue(root, 'h'),
2597
2742
  // Substituted here rather than in the component: `<bech32>` is a NIP-89
2598
2743
  // detail, and the widget's job is to draw a link, not to know the spec.
@@ -3073,7 +3218,7 @@ function withPeople({ object, children }: AssembledObject, people: People): Fore
3073
3218
  */
3074
3219
  function declaredChildSpec(projection: {
3075
3220
  slots: Record<string, SlotSpec | SlotSpec[]>
3076
- }): { kind: number; via: string; limit?: number; match?: string } | undefined {
3221
+ }): { kind: number; via: string; limit?: number; match?: string; movedBy?: string } | undefined {
3077
3222
  const spec = projection.slots.list
3078
3223
  return !Array.isArray(spec) ? spec?.children : undefined
3079
3224
  }
@@ -3108,15 +3253,24 @@ function parentRefOf(
3108
3253
  direction lets Ship's project list its issues without an issue knowing what
3109
3254
  a project is; this one lets a topic sit under a project, an issue, or a kind
3110
3255
  nobody has met, without that kind's owner declaring bare files as children.
3111
- Re-parenting is a `parent` change event, seeded by the root tag, the way an
3112
- 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).
3113
3258
  */
3114
- if (kind === KIND_BARE_FILE) {
3259
+ const movedBy = movedByOf(manifest, kind)
3260
+ if (movedBy) {
3115
3261
  // A folded empty value is a move to the top, not an absence: falling back
3116
3262
  // to the root tag would put the file straight back under the parent it
3117
3263
  // was moved out of (FOL-4).
3118
- const moved = folded[BARE_FILE_PARENT_FIELD]
3119
- 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) {
3120
3274
  return root.tags.find((t) => t[0] === 'a' && t[1] && /^\d+:[0-9a-f]{64}:/.test(t[1]))?.[1]
3121
3275
  }
3122
3276
  for (const [parentKind, projection] of Object.entries(manifest.projections ?? {})) {
@@ -3137,6 +3291,34 @@ function parentRefOf(
3137
3291
  return undefined
3138
3292
  }
3139
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
+
3140
3322
  /** Both halves of the question a disclosure control asks. */
3141
3323
  function listsChildrenOf(
3142
3324
  projection: { slots: Record<string, SlotSpec | SlotSpec[]> },
@@ -3270,7 +3452,7 @@ function buildChildObject(args: {
3270
3452
  // an inconsistent shape is what makes a consumer defensive about a value it
3271
3453
  // should be able to trust.
3272
3454
  parentRef: parentRefOf(manifest, root.kind, root),
3273
- ...(root.kind === KIND_BARE_FILE ? { parentField: BARE_FILE_PARENT_FIELD } : {}),
3455
+ ...parentFieldsOf(manifest, root.kind),
3274
3456
  folder: tagValue(root, 'h'),
3275
3457
  /*
3276
3458
  `<bech32>` is whichever form this object actually has.
@@ -3910,6 +4092,51 @@ export async function resolveFolderProject(
3910
4092
  */
3911
4093
  const isAddressableKind = (kind: number) => kind >= 30000 && kind < 40000
3912
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
+
3913
4140
  /**
3914
4141
  * The event an object-creating action publishes.
3915
4142
  *
@@ -3929,6 +4156,7 @@ function buildCreationEvent(args: {
3929
4156
  folder: string
3930
4157
  value: string | Record<string, string>
3931
4158
  newId?: string
4159
+ contentFormat?: string
3932
4160
  pubkey: string
3933
4161
  createdAtMs: number
3934
4162
  }): UnsignedActionEvent | string {
@@ -3982,6 +4210,20 @@ function buildCreationEvent(args: {
3982
4210
  }
3983
4211
  const bodyField = bodyFields[0]
3984
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
+
3985
4227
  const tags: string[][] = []
3986
4228
  if (isAddressableKind(declared.emits.kind)) tags.push(['d', newId!])
3987
4229
  // A property's name is the tag it writes, unless it declared `content`. See
@@ -3995,7 +4237,7 @@ function buildCreationEvent(args: {
3995
4237
  if (declared.emits.setTag && declared.emits.toAddressOf === 'self') {
3996
4238
  tags.push([declared.emits.setTag, address])
3997
4239
  }
3998
- tags.push(['h', folder])
4240
+ tags.push([placement, folder], ...prose)
3999
4241
 
4000
4242
  return {
4001
4243
  pubkey: args.pubkey,
@@ -4006,7 +4248,8 @@ function buildCreationEvent(args: {
4006
4248
  }
4007
4249
  }
4008
4250
 
4009
- export function buildActionEvent(args: {
4251
+ /** What {@link buildActionEvent} and {@link buildActionEvents} are handed. */
4252
+ export interface ActionEventArgs {
4010
4253
  manifest: { records?: RecordsRule; actions?: ManifestAction[]; vocabularies?: Manifest['vocabularies'] }
4011
4254
  kind: number
4012
4255
  /** Address of the object being acted on. */
@@ -4041,9 +4284,97 @@ export function buildActionEvent(args: {
4041
4284
  * Refused on any action that is not a comment: nothing else has a parent.
4042
4285
  */
4043
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
4044
4297
  pubkey: string
4045
4298
  createdAtMs: number
4046
- }): UnsignedActionEvent | string {
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 {
4047
4378
  const { manifest, kind, address, folder, actionId, value, replyTo } = args
4048
4379
  const records = manifest.records
4049
4380
  const declared = manifest.actions?.find((a) => a.id === actionId)
@@ -4054,7 +4385,7 @@ export function buildActionEvent(args: {
4054
4385
  return `"${declared.label}" does not apply to a kind ${kind}.`
4055
4386
  }
4056
4387
 
4057
- const isCreation = declared.input?.type === 'object' && !!declared.input.properties
4388
+ const isCreation = isCreationAction(declared)
4058
4389
 
4059
4390
  // A reply is a comment with a parent — what the scalar path below builds for
4060
4391
  // an action that is neither a deletion nor a change. Refused here, before any
@@ -4062,6 +4393,11 @@ export function buildActionEvent(args: {
4062
4393
  if (replyTo && (isCreation || declared.emits.kind === KIND_DELETION || declared.emits.field)) {
4063
4394
  return `"${declared.label}" is not a comment, so it cannot reply to one.`
4064
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
+ }
4065
4401
 
4066
4402
  // An object-creating action is a different event entirely — a new object
4067
4403
  // rather than a change to one — so it branches before the scalar path.
@@ -4129,12 +4465,21 @@ export function buildActionEvent(args: {
4129
4465
  }
4130
4466
  }
4131
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
+
4132
4476
  const tags: string[][] = declared.emits.field
4133
4477
  ? [
4134
4478
  [records.targetTag, address],
4135
4479
  [records.fieldTag, declared.emits.field],
4136
4480
  [records.valueTag, value],
4137
4481
  ['h', folder],
4482
+ ...(formatTag ? [formatTag] : []),
4138
4483
  ]
4139
4484
  : // NIP-22 comment. Built from the ratified NIP rather than from the
4140
4485
  // manifest, which is legitimate precisely because no app owns kind:1111 —
@@ -4164,6 +4509,7 @@ export function buildActionEvent(args: {
4164
4509
  // second would be separated by event id — arbitrarily, and differently
4165
4510
  // depending on which app you asked (FRICTION.md A6).
4166
4511
  if (records.order?.includes('ts')) tags.push(['ts', String(args.createdAtMs)])
4512
+ tags.push(...files)
4167
4513
 
4168
4514
  return {
4169
4515
  pubkey: args.pubkey,