@estiva-app/conversation 0.4.0 → 0.5.1

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/CHANGELOG.md CHANGED
@@ -6,6 +6,37 @@ none. A change to how an event is read is a MINOR in `0.x` even when no
6
6
  signature moved, because two apps on different versions would then disagree
7
7
  about a conversation.
8
8
 
9
+ ## 0.5.1 — 2026-10-03
10
+
11
+ **`[` never offers the file you are writing in** (PEE-21, Miky 2026-10-03):
12
+ its messages already lead Messages, and a widget pointing back at the page
13
+ you are on is no use. `rankReferences` takes `exclude`, the addresses no Files
14
+ tier offers. SPEC: none — nothing read or written changed.
15
+
16
+ ## 0.5.0 — 2026-10-03
17
+
18
+ **What `[` offers, and in what order** (PEE-21, CON-26's ranking, Miky
19
+ 2026-10-02/03). Needs protocol 0.24.0, unchanged.
20
+
21
+ - `rankReferences({messages, files, query, ownKinds?, caps?})` — two capped
22
+ sections, Messages (this thread or file, then its parent) above Files (this
23
+ Folder, then recently read, then search hits only once something is typed).
24
+ Typed, a better title match beats a higher tier; an archived file goes after
25
+ every other row of the same match, typed or not, and an open issue before a
26
+ closed one; the app's own kinds break what ties are left. `REFERENCE_CAPS`
27
+ is 4 and 6.
28
+ - `referenceMatch(text, query)` — 4 whole, 3 start, 2 word start, 1 anywhere.
29
+ - `fileReference(address)` — `nostr:naddr…` with no relay hint, the bytes a
30
+ pasted link resolves to.
31
+ - `referenceSearch({search})` — the search tier per keystroke: debounced,
32
+ cached, a failure answered as no hits for `retryMs` (5s) and then asked
33
+ again, listeners told when an answer lands. `reset()` it when the signed-in
34
+ person changes.
35
+
36
+ **SPEC:** none of §6 or §9 changes how this package reads or writes. A file
37
+ pick writes what a paste writes and earns `["a", <address>]` through
38
+ `referenceTagsFor`, as §13.1 already says; ranking is a client's choice.
39
+
9
40
  ## 0.4.0 — 2026-10-02
10
41
 
11
42
  **A reference records which message it points at** (CON-25, Miky
package/README.md CHANGED
@@ -26,6 +26,7 @@ pass, the clock is a `createdAtMs` you pass, and drafts take their storage.
26
26
  | threading | §6.4 *Replies* | `parentOf`, `groupThreads` |
27
27
  | writing | §6.4 | `buildComment`, `buildReply`, `referenceTagsFor`, `mentionTagsFor` |
28
28
  | what a composer's pick writes | §13.1 | `mentionText`, `messageReference`, `urgentTagsFor`, `URGENT_TAG` |
29
+ | what `[` offers, and in what order | §13.1 | `rankReferences`, `referenceMatch`, `fileReference`, `referenceSearch`, `MESSAGE_TIER`, `FILE_TIER`, `REFERENCE_CAPS` |
29
30
  | ordering | §6.2, §6.3 | `trustedTs`, `orderingMs`, `byOrder` |
30
31
  | edits and attachments | §6.8 | `editTargetOf`, `foldEdits`, `foldAttachments` |
31
32
  | reactions | §6.6 | `REACTION_HORIZON`, `reactionHorizon`, `reactionTargetOf`, `reactionEmojiOf`, `foldReactions` |
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  * apps: it imports no app's data layer, opens no socket, and takes every
13
13
  * environment touch — the relay read, the clock, storage — as a parameter.
14
14
  */
15
- export declare const CONVERSATION_VERSION = "0.4.0";
15
+ export declare const CONVERSATION_VERSION = "0.5.1";
16
16
  export { KIND_MESSAGE, KIND_COMMENT, KIND_EDIT, KIND_REACTION, KIND_DELETION, KIND_ASSERTION, isConversationKind, isEventId, } from './kinds.js';
17
17
  export { trustedTs, orderingMs, byOrder } from './order.js';
18
18
  export { namedInBody, isReply, anchorsOf, isCommentOn, referencesAddress, strengthOn, threadStrength, referenceTagsFor, mentionTagsFor, peopleNamedInBody, MAX_MENTIONED_PEOPLE, type Strength, } from './strength.js';
@@ -22,6 +22,7 @@ export { REACTION_HORIZON, REACTION_EMOJI, reactionTargetOf, reactionEmojiOf, re
22
22
  export { decorationsOf, type Decoration, type Decorations, type Resolution, type QueryFn } from './decorations.js';
23
23
  export { buildComment, buildReply, offersEditAndDelete, type CommentRef } from './builders.js';
24
24
  export { eventsNamedInBody, mentionText, messageReference, quoteTagsFor, URGENT_TAG, urgentTagsFor } from './compose.js';
25
+ export { FILE_TIER, fileReference, MESSAGE_TIER, rankReferences, REFERENCE_CAPS, referenceMatch, referenceSearch, type RankedReferences, type RankReferencesInput, type ReferenceCandidate, type ReferenceSearch, type ReferenceSearchFn, type ReferenceSearchOptions, type ReferenceType, } from './references.js';
25
26
  export { KIND_CHANGE, MEMBER_FIELD_PREFIX, memberField, memberOfField, mentions, streamOf, membershipOf, membersOf, membershipFilters, candidateFilesOf, buildMembershipChange, MUTED_D_TAG, APPDATA_TAG, parseMutedBlob, serializeMutedBlob, buildMutedEvent, mutedFilter, mutedFromFollowed, type Membership, type MutedList, } from './membership.js';
26
27
  export { READ_STATE_TAG, READ_STATE_D_PREFIX, MAX_CONTEXTS, MAX_CONTEXT_ID_BYTES, MAX_TIMESTAMP, MAX_CLIENT_ID_BYTES, MAX_BLOB_BYTES, MAX_CONTEXTS_BYTES, READ_STATE_HORIZON_DAYS, channelContext, fileContext, threadContext, messageContext, toContextSeconds, isPublishableContextId, loadSlotIdentity, rotateSlotId, readStateDTag, parseReadStateBlob, serializeReadStateBlob, capContextsToBytes, advanceContexts, buildReadStateEvent, allSlotsFilter, mergeSlots, classifyOwnSlots, effectiveReadAt, fetchReadState, publishReadState, type SlotIdentity, type SlotStorage, type SlotSource, type RandomBytes, type ReadStateBlob, type CappedContexts, type SlotBlob, type OwnSlotVerdict, type Nip44, type FetchedReadState, } from './readState.js';
27
28
  export { unreadIn, isUnread, type StreamJudge } from './unread.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,UAAU,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,E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EACd,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,KAAK,EACV,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,KAAK,UAAU,EACf,KAAK,YAAY,GAClB,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,UAAU,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE3D,OAAO,EACL,WAAW,EACX,OAAO,EACP,SAAS,EACT,WAAW,EACX,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,i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EACf,WAAW,EACX,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,SAAS,GACf,MAAM,iBAAiB,CAAA;AAExB,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACpB,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,KAAK,EACV,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,KAAK,UAAU,EACf,KAAK,YAAY,GAClB,MAAM,aAAa,CAAA"}
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * apps: it imports no app's data layer, opens no socket, and takes every
13
13
  * environment touch — the relay read, the clock, storage — as a parameter.
14
14
  */
15
- export const CONVERSATION_VERSION = '0.4.0';
15
+ export const CONVERSATION_VERSION = '0.5.1';
16
16
  export { KIND_MESSAGE, KIND_COMMENT, KIND_EDIT, KIND_REACTION, KIND_DELETION, KIND_ASSERTION, isConversationKind, isEventId, } from './kinds.js';
17
17
  export { trustedTs, orderingMs, byOrder } from './order.js';
18
18
  export { namedInBody, isReply, anchorsOf, isCommentOn, referencesAddress, strengthOn, threadStrength, referenceTagsFor, mentionTagsFor, peopleNamedInBody, MAX_MENTIONED_PEOPLE, } from './strength.js';
@@ -22,6 +22,7 @@ export { REACTION_HORIZON, REACTION_EMOJI, reactionTargetOf, reactionEmojiOf, re
22
22
  export { decorationsOf } from './decorations.js';
23
23
  export { buildComment, buildReply, offersEditAndDelete } from './builders.js';
24
24
  export { eventsNamedInBody, mentionText, messageReference, quoteTagsFor, URGENT_TAG, urgentTagsFor } from './compose.js';
25
+ export { FILE_TIER, fileReference, MESSAGE_TIER, rankReferences, REFERENCE_CAPS, referenceMatch, referenceSearch, } from './references.js';
25
26
  export { KIND_CHANGE, MEMBER_FIELD_PREFIX, memberField, memberOfField, mentions, streamOf, membershipOf, membersOf, membershipFilters, candidateFilesOf, buildMembershipChange, MUTED_D_TAG, APPDATA_TAG, parseMutedBlob, serializeMutedBlob, buildMutedEvent, mutedFilter, mutedFromFollowed, } from './membership.js';
26
27
  export { READ_STATE_TAG, READ_STATE_D_PREFIX, MAX_CONTEXTS, MAX_CONTEXT_ID_BYTES, MAX_TIMESTAMP, MAX_CLIENT_ID_BYTES, MAX_BLOB_BYTES, MAX_CONTEXTS_BYTES, READ_STATE_HORIZON_DAYS, channelContext, fileContext, threadContext, messageContext, toContextSeconds, isPublishableContextId, loadSlotIdentity, rotateSlotId, readStateDTag, parseReadStateBlob, serializeReadStateBlob, capContextsToBytes, advanceContexts, buildReadStateEvent, allSlotsFilter, mergeSlots, classifyOwnSlots, effectiveReadAt, fetchReadState, publishReadState, } from './readState.js';
27
28
  export { unreadIn, isUnread } from './unread.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAA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EACvB,cAAc,EACd,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,gBAAgB,GAWjB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAoB,MAAM,aAAa,CAAA;AAElE,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,gBAAgB,EAChB,eAAe,GAGhB,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,OAAO,CAAA;AAE3C,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,aAAa,EACb,aAAa,EACb,cAAc,EACd,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE3D,OAAO,EACL,WAAW,EACX,OAAO,EACP,SAAS,EACT,WAAW,EACX,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,oBAAoB,GAErB,MAAM,eAAe,CAAA;AAEtB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAiB,MAAM,cAAc,CAAA;AAEpE,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,eAAe,EAAiB,MAAM,YAAY,CAAA;AAEnG,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,cAAc,GAIf,MAAM,gBAAg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as the row's type word says it (label objects by type, not app). */
2
+ export type ReferenceType = 'message' | 'issue' | 'project' | 'topic';
3
+ /** Something `[` can offer. */
4
+ export interface ReferenceCandidate {
5
+ /** The event id of a message, the `kind:pubkey:d` address of a file. Unique across the list. */
6
+ id: string;
7
+ /** `nostr:…`, exactly as the body will carry it: {@link fileReference} or `messageReference`. */
8
+ uri: string;
9
+ type: ReferenceType;
10
+ kind: number;
11
+ /** A file's current title; a message's author. */
12
+ title: string;
13
+ /** An issue's project title, a message's opening words; `''` when there is none. */
14
+ caption: string;
15
+ /** A message's text, matched beside `title`. Files match on `title` only. */
16
+ search?: string;
17
+ /** 0 is closest: {@link MESSAGE_TIER} or {@link FILE_TIER}. */
18
+ tier: number;
19
+ /** A done or cancelled issue: offered, after an open one on an equal match. */
20
+ closed?: boolean;
21
+ /**
22
+ * An archived file, or an issue in an archived project: offered at the lowest
23
+ * priority — after every row that is not, on an equal match (Miky, 2026-10-03).
24
+ */
25
+ archived?: boolean;
26
+ /** When it was written or last read, in seconds — newer first within a tier. */
27
+ at?: number;
28
+ }
29
+ /** Where a message sits relative to the box you are writing in. */
30
+ export declare const MESSAGE_TIER: {
31
+ readonly here: 0;
32
+ readonly parent: 1;
33
+ };
34
+ /** Where a file sits relative to you. `search` only ever comes from typing. */
35
+ export declare const FILE_TIER: {
36
+ readonly folder: 0;
37
+ readonly recent: 1;
38
+ readonly search: 2;
39
+ };
40
+ /** How many rows each section shows (Miky, 2026-10-03): the box stays at the old list's height. */
41
+ export declare const REFERENCE_CAPS: {
42
+ readonly messages: 4;
43
+ readonly files: 6;
44
+ };
45
+ export interface RankedReferences {
46
+ messages: ReferenceCandidate[];
47
+ files: ReferenceCandidate[];
48
+ }
49
+ export interface RankReferencesInput {
50
+ messages: readonly ReferenceCandidate[];
51
+ files: readonly ReferenceCandidate[];
52
+ /** What was typed after `[`. */
53
+ query: string;
54
+ /** The kinds the app itself writes — the last tie-breaker. */
55
+ ownKinds?: readonly number[];
56
+ caps?: {
57
+ messages: number;
58
+ files: number;
59
+ };
60
+ /**
61
+ * Files never offered, by address: the file you are writing in, whose
62
+ * messages already lead Messages (Miky, 2026-10-03).
63
+ */
64
+ exclude?: readonly string[];
65
+ }
66
+ /**
67
+ * How well `text` holds `query`: 4 the whole of it, 3 its start, 2 the start of
68
+ * a word, 1 anywhere — or every word of the query at a word's start. 0 is no
69
+ * match. Case and runs of spaces are ignored.
70
+ */
71
+ export declare function referenceMatch(text: string, query: string): number;
72
+ /**
73
+ * The two sections `[` draws, each ranked and capped.
74
+ *
75
+ * Nothing in the `search` tier is offered with nothing typed, nor anything that
76
+ * does not match what was typed. Ties end on recency, then the title, so the
77
+ * list holds still between keystrokes.
78
+ */
79
+ export declare function rankReferences({ messages, files, query, ownKinds, caps, exclude }: RankReferencesInput): RankedReferences;
80
+ /**
81
+ * A file as the body references it: `nostr:naddr…` with no relay hint, the
82
+ * same bytes a pasted link resolves to — so it earns its `["a", <address>]`
83
+ * through `referenceTagsFor` and draws as the same widget (SPEC §13.1). The
84
+ * title is never in the body: a file from a private Folder named in a wider
85
+ * one leaks nothing but its pointer.
86
+ *
87
+ * `address` is `kind:pubkey:d`; anything else throws.
88
+ */
89
+ export declare function fileReference(address: string): string;
90
+ /** What a {@link referenceSearch} asks the relay for: the files whose title holds `query`. */
91
+ export type ReferenceSearchFn = (query: string) => Promise<readonly ReferenceCandidate[]>;
92
+ export interface ReferenceSearch {
93
+ /**
94
+ * The search tier for `query`: what the relay last answered for it, or —
95
+ * while it is asked — for the longest query before it that it answered.
96
+ * Asks it, after a pause, when it has not been asked.
97
+ */
98
+ hits(query: string): readonly ReferenceCandidate[];
99
+ /** Called when an answer lands; returns the unsubscribe. */
100
+ subscribe(listener: () => void): () => void;
101
+ /**
102
+ * Drops what is pending and what was answered. Call it when the signed-in
103
+ * person changes: answers are kept by the text asked, not by who asked, and
104
+ * the last person's hits name files the next one may not be able to read.
105
+ */
106
+ reset(): void;
107
+ }
108
+ export interface ReferenceSearchOptions {
109
+ search: ReferenceSearchFn;
110
+ /** The pause after a keystroke before asking. Default 200ms. */
111
+ delayMs?: number;
112
+ /** How long a failed query answers no hits before it may be asked again. Default 5s. */
113
+ retryMs?: number;
114
+ /** Shorter queries ask nothing. Default 2. */
115
+ minLength?: number;
116
+ }
117
+ /**
118
+ * The third Files tier, as the list asks for it on every keystroke: answers
119
+ * now from what it holds, and asks the relay behind it.
120
+ *
121
+ * The rows already on screen never wait for the relay: a slow or failing
122
+ * search leaves them as they are, with no spinner and no error row
123
+ * (PEE-21). A failure answers no hits for `retryMs`, so a rate limit is not
124
+ * hammered on every render, and is then forgotten, so one blip does not hide
125
+ * that query for the rest of the session. Answers are filtered again by
126
+ * {@link rankReferences}, so a shorter query's hits shown meanwhile never
127
+ * offer a row the typed text does not match.
128
+ *
129
+ * Only the pause is cancelled by the next keystroke: a query already asked
130
+ * keeps its answer, which is still true of that query.
131
+ */
132
+ export declare function referenceSearch({ search, delayMs, retryMs, minLength }: ReferenceSearchOptions): ReferenceSearch;
133
+ //# sourceMappingURL=references.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"references.d.ts","sourceRoot":"","sources":["../src/references.ts"],"names":[],"mappings":"AAuBA,+FAA+F;AAC/F,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,CAAA;AAErE,+BAA+B;AAC/B,MAAM,WAAW,kBAAkB;IACjC,gGAAgG;IAChG,EAAE,EAAE,MAAM,CAAA;IACV,iGAAiG;IACjG,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,aAAa,CAAA;IACnB,IAAI,EAAE,MAAM,CAAA;IACZ,kDAAkD;IAClD,KAAK,EAAE,MAAM,CAAA;IACb,oFAAoF;IACpF,OAAO,EAAE,MAAM,CAAA;IACf,6EAA6E;IAC7E,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,+DAA+D;IAC/D,IAAI,EAAE,MAAM,CAAA;IACZ,+EAA+E;IAC/E,MAAM,C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CAAC,SAAS,kBAAkB,EAAE,CAAC,CAAA;AAKzF,MAAM,WAAW,eAAe;IAC9B;;;;OAIG;IACH,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,kBAAkB,EAAE,CAAA;IAClD,4DAA4D;IAC5D,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAA;IAC3C;;;;OAIG;IACH,KAAK,IAAI,IAAI,CAAA;CACd;AAED,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,iBAAiB,CAAA;IACzB,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,wFAAwF;IACxF,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,8CAA8C;IAC9C,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAAC,EAAE,MAAM,EAAE,OAAa,EAAE,OAAc,EAAE,SAAa,EAAE,EAAE,sBAAsB,GAAG,eAAe,CAgEjI"}
@@ -0,0 +1,204 @@
1
+ /**
2
+ * What `[` offers, and in what order — CON-26's ranking (Miky, 2026-10-02),
3
+ * in one place for every app (PEE-21).
4
+ *
5
+ * Two capped sections, Messages above Files:
6
+ *
7
+ * - **Messages:** this thread or file first, then the parent file's.
8
+ * - **Files:** this Folder first, then files you read recently (your §11 read
9
+ * markers), then everything else, which you reach only by typing (relay
10
+ * search).
11
+ *
12
+ * With nothing typed the tiers set the order. Once you type, a better title
13
+ * match beats a higher tier; an open issue goes before a done or cancelled
14
+ * one on an equal match (Miky, 2026-10-03); the app's own kinds only break the
15
+ * ties that are left.
16
+ *
17
+ * The menu that draws the result is an editor's (`@estiva-app/ui/editor`'s
18
+ * `ReferenceTrigger`); this is the half a client that does not use React can
19
+ * take too. Where the candidates come from — a Folder's files, the read
20
+ * markers, a relay search — is the app's: each app holds them differently.
21
+ */
22
+ import { addrToNaddr } from '@estiva-app/protocol';
23
+ /** Where a message sits relative to the box you are writing in. */
24
+ export const MESSAGE_TIER = { here: 0, parent: 1 };
25
+ /** Where a file sits relative to you. `search` only ever comes from typing. */
26
+ export const FILE_TIER = { folder: 0, recent: 1, search: 2 };
27
+ /** How many rows each section shows (Miky, 2026-10-03): the box stays at the old list's height. */
28
+ export const REFERENCE_CAPS = { messages: 4, files: 6 };
29
+ const normalize = (text) => text.toLowerCase().replace(/\s+/g, ' ').trim();
30
+ const isWordStart = (text, at) => at === 0 || !/[\p{L}\p{N}]/u.test(text[at - 1]);
31
+ /**
32
+ * How well `text` holds `query`: 4 the whole of it, 3 its start, 2 the start of
33
+ * a word, 1 anywhere — or every word of the query at a word's start. 0 is no
34
+ * match. Case and runs of spaces are ignored.
35
+ */
36
+ export function referenceMatch(text, query) {
37
+ const t = normalize(text);
38
+ const q = normalize(query);
39
+ if (!q)
40
+ return 0;
41
+ if (t === q)
42
+ return 4;
43
+ if (t.startsWith(q))
44
+ return 3;
45
+ let at = t.indexOf(q);
46
+ if (at < 0) {
47
+ const words = q.split(' ');
48
+ if (words.length < 2)
49
+ return 0;
50
+ const starts = (w) => {
51
+ for (let i = t.indexOf(w); i >= 0; i = t.indexOf(w, i + 1))
52
+ if (isWordStart(t, i))
53
+ return true;
54
+ return false;
55
+ };
56
+ return words.every(starts) ? 1 : 0;
57
+ }
58
+ for (; at >= 0; at = t.indexOf(q, at + 1))
59
+ if (isWordStart(t, at))
60
+ return 2;
61
+ return 1;
62
+ }
63
+ /** Keeps each id once, at its closest tier. */
64
+ function closest(candidates) {
65
+ const best = new Map();
66
+ for (const c of candidates) {
67
+ const known = best.get(c.id);
68
+ if (!known || c.tier < known.tier)
69
+ best.set(c.id, c);
70
+ }
71
+ return [...best.values()];
72
+ }
73
+ const newer = (a, b) => (b.at ?? 0) - (a.at ?? 0);
74
+ /**
75
+ * The two sections `[` draws, each ranked and capped.
76
+ *
77
+ * Nothing in the `search` tier is offered with nothing typed, nor anything that
78
+ * does not match what was typed. Ties end on recency, then the title, so the
79
+ * list holds still between keystrokes.
80
+ */
81
+ export function rankReferences({ messages, files, query, ownKinds = [], caps = REFERENCE_CAPS, exclude = [] }) {
82
+ const typed = normalize(query) !== '';
83
+ const own = new Set(ownKinds);
84
+ const excluded = new Set(exclude);
85
+ const ownFirst = (a, b) => Number(!own.has(a.kind)) - Number(!own.has(b.kind));
86
+ const byTitle = (a, b) => a.title.localeCompare(b.title);
87
+ const messageScore = (m) => Math.max(referenceMatch(m.title, query), referenceMatch(m.search ?? m.caption, query));
88
+ const shownMessages = closest(messages)
89
+ .map((m) => ({ m, score: typed ? messageScore(m) : 0 }))
90
+ .filter(({ score }) => !typed || score > 0)
91
+ .sort((a, b) => b.score - a.score || a.m.tier - b.m.tier || newer(a.m, b.m) || a.m.id.localeCompare(b.m.id))
92
+ .slice(0, caps.messages)
93
+ .map(({ m }) => m);
94
+ const shownFiles = closest(files)
95
+ .filter((f) => !excluded.has(f.id) && (typed || f.tier !== FILE_TIER.search))
96
+ .map((f) => ({ f, score: typed ? referenceMatch(f.title, query) : 0 }))
97
+ .filter(({ score }) => !typed || score > 0)
98
+ .sort((a, b) => b.score - a.score ||
99
+ Number(!!a.f.archived) - Number(!!b.f.archived) ||
100
+ (typed ? Number(!!a.f.closed) - Number(!!b.f.closed) || a.f.tier - b.f.tier : a.f.tier - b.f.tier || Number(!!a.f.closed) - Number(!!b.f.closed)) ||
101
+ ownFirst(a.f, b.f) ||
102
+ newer(a.f, b.f) ||
103
+ byTitle(a.f, b.f))
104
+ .slice(0, caps.files)
105
+ .map(({ f }) => f);
106
+ return { messages: shownMessages, files: shownFiles };
107
+ }
108
+ /**
109
+ * A file as the body references it: `nostr:naddr…` with no relay hint, the
110
+ * same bytes a pasted link resolves to — so it earns its `["a", <address>]`
111
+ * through `referenceTagsFor` and draws as the same widget (SPEC §13.1). The
112
+ * title is never in the body: a file from a private Folder named in a wider
113
+ * one leaks nothing but its pointer.
114
+ *
115
+ * `address` is `kind:pubkey:d`; anything else throws.
116
+ */
117
+ export function fileReference(address) {
118
+ return `nostr:${addrToNaddr(address)}`;
119
+ }
120
+ // The package targets no runtime's lib, and a pause is all it needs of one.
121
+ const timers = globalThis;
122
+ /**
123
+ * The third Files tier, as the list asks for it on every keystroke: answers
124
+ * now from what it holds, and asks the relay behind it.
125
+ *
126
+ * The rows already on screen never wait for the relay: a slow or failing
127
+ * search leaves them as they are, with no spinner and no error row
128
+ * (PEE-21). A failure answers no hits for `retryMs`, so a rate limit is not
129
+ * hammered on every render, and is then forgotten, so one blip does not hide
130
+ * that query for the rest of the session. Answers are filtered again by
131
+ * {@link rankReferences}, so a shorter query's hits shown meanwhile never
132
+ * offer a row the typed text does not match.
133
+ *
134
+ * Only the pause is cancelled by the next keystroke: a query already asked
135
+ * keeps its answer, which is still true of that query.
136
+ */
137
+ export function referenceSearch({ search, delayMs = 200, retryMs = 5000, minLength = 2 }) {
138
+ const answered = new Map();
139
+ const asking = new Set();
140
+ const listeners = new Set();
141
+ let paused = null;
142
+ const cancel = () => {
143
+ if (paused)
144
+ timers.clearTimeout(paused.timer);
145
+ paused = null;
146
+ };
147
+ const ask = (query) => {
148
+ cancel();
149
+ const timer = timers.setTimeout(() => {
150
+ paused = null;
151
+ asking.add(query);
152
+ search(query)
153
+ .then((found) => found, () => {
154
+ const failed = [];
155
+ timers.setTimeout(() => {
156
+ if (answered.get(query) === failed)
157
+ answered.delete(query);
158
+ }, retryMs);
159
+ return failed;
160
+ })
161
+ .then((found) => {
162
+ if (!asking.delete(query))
163
+ return;
164
+ answered.set(query, found.length ? found.map((f) => ({ ...f, tier: FILE_TIER.search })) : found);
165
+ // A session's worth of queries; the oldest goes first.
166
+ if (answered.size > 64)
167
+ answered.delete(answered.keys().next().value);
168
+ for (const listener of listeners)
169
+ listener();
170
+ });
171
+ }, delayMs);
172
+ paused = { query, timer };
173
+ };
174
+ return {
175
+ hits(raw) {
176
+ const query = normalize(raw);
177
+ if (query.length < minLength) {
178
+ cancel();
179
+ return [];
180
+ }
181
+ const known = answered.get(query);
182
+ if (known)
183
+ return known;
184
+ if (paused?.query !== query && !asking.has(query))
185
+ ask(query);
186
+ for (let n = query.length - 1; n >= minLength; n--) {
187
+ const shorter = answered.get(query.slice(0, n).trim());
188
+ if (shorter)
189
+ return shorter;
190
+ }
191
+ return [];
192
+ },
193
+ subscribe(listener) {
194
+ listeners.add(listener);
195
+ return () => listeners.delete(listener);
196
+ },
197
+ reset() {
198
+ cancel();
199
+ asking.clear();
200
+ answered.clear();
201
+ },
202
+ };
203
+ }
204
+ //# sourceMappingURL=references.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"references.js","sourceRoot":"","sources":["../src/references.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAgClD,mEAAmE;AACnE,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAW,CAAA;AAE3D,+EAA+E;AAC/E,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAW,CAAA;AAErE,mGAAmG;AACnG,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAW,CAAA;AAsBhE,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAA;AAElF,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,EAAU,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,CAAE,CAAC,CAAA;AAElG;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY,EAAE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AAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YACjC,IAAI,KAAK;gBAAE,OAAO,KAAK,CAAA;YACvB,IAAI,MAAM,EAAE,KAAK,KAAK,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC;gBAAE,GAAG,CAAC,KAAK,CAAC,CAAA;YAC7D,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC,EAAE,EAAE,CAAC;gBACnD,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;gBACtD,IAAI,OAAO;oBAAE,OAAO,OAAO,CAAA;YAC7B,CAAC;YACD,OAAO,EAAE,CAAA;QACX,CAAC;QACD,SAAS,CAAC,QAAQ;YAChB,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;YACvB,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;QACzC,CAAC;QACD,KAAK;YACH,MAAM,EAAE,CAAA;YACR,MAAM,CAAC,KAAK,EAAE,CAAA;YACd,QAAQ,CAAC,KAAK,EAAE,CAAA;QAClB,CAAC;KACF,CAAA;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/conversation",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "The conversation rules of the Estiva SPEC (§6.2–§6.8, §11): comment and mention strengths, threading, the edit, reaction and attachment folds, NIP-22 comment and reply builders, drafts, NIP-RS read state, membership and unread. A convenience an app adopts, never a requirement.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  * apps: it imports no app's data layer, opens no socket, and takes every
13
13
  * environment touch — the relay read, the clock, storage — as a parameter.
14
14
  */
15
- export const CONVERSATION_VERSION = '0.4.0'
15
+ export const CONVERSATION_VERSION = '0.5.1'
16
16
 
17
17
  export {
18
18
  KIND_MESSAGE,
@@ -66,6 +66,23 @@ export { buildComment, buildReply, offersEditAndDelete, type CommentRef } from '
66
66
 
67
67
  export { eventsNamedInBody, mentionText, messageReference, quoteTagsFor, URGENT_TAG, urgentTagsFor } from './compose.js'
68
68
 
69
+ export {
70
+ FILE_TIER,
71
+ fileReference,
72
+ MESSAGE_TIER,
73
+ rankReferences,
74
+ REFERENCE_CAPS,
75
+ referenceMatch,
76
+ referenceSearch,
77
+ type RankedReferences,
78
+ type RankReferencesInput,
79
+ type ReferenceCandidate,
80
+ type ReferenceSearch,
81
+ type ReferenceSearchFn,
82
+ type ReferenceSearchOptions,
83
+ type ReferenceType,
84
+ } from './references.js'
85
+
69
86
  export {
70
87
  KIND_CHANGE,
71
88
  MEMBER_FIELD_PREFIX,
@@ -0,0 +1,290 @@
1
+ /**
2
+ * What `[` offers, and in what order — CON-26's ranking (Miky, 2026-10-02),
3
+ * in one place for every app (PEE-21).
4
+ *
5
+ * Two capped sections, Messages above Files:
6
+ *
7
+ * - **Messages:** this thread or file first, then the parent file's.
8
+ * - **Files:** this Folder first, then files you read recently (your §11 read
9
+ * markers), then everything else, which you reach only by typing (relay
10
+ * search).
11
+ *
12
+ * With nothing typed the tiers set the order. Once you type, a better title
13
+ * match beats a higher tier; an open issue goes before a done or cancelled
14
+ * one on an equal match (Miky, 2026-10-03); the app's own kinds only break the
15
+ * ties that are left.
16
+ *
17
+ * The menu that draws the result is an editor's (`@estiva-app/ui/editor`'s
18
+ * `ReferenceTrigger`); this is the half a client that does not use React can
19
+ * take too. Where the candidates come from — a Folder's files, the read
20
+ * markers, a relay search — is the app's: each app holds them differently.
21
+ */
22
+ import { addrToNaddr } from '@estiva-app/protocol'
23
+
24
+ /** What a reference names, as the row's type word says it (label objects by type, not app). */
25
+ export type ReferenceType = 'message' | 'issue' | 'project' | 'topic'
26
+
27
+ /** Something `[` can offer. */
28
+ export interface ReferenceCandidate {
29
+ /** The event id of a message, the `kind:pubkey:d` address of a file. Unique across the list. */
30
+ id: string
31
+ /** `nostr:…`, exactly as the body will carry it: {@link fileReference} or `messageReference`. */
32
+ uri: string
33
+ type: ReferenceType
34
+ kind: number
35
+ /** A file's current title; a message's author. */
36
+ title: string
37
+ /** An issue's project title, a message's opening words; `''` when there is none. */
38
+ caption: string
39
+ /** A message's text, matched beside `title`. Files match on `title` only. */
40
+ search?: string
41
+ /** 0 is closest: {@link MESSAGE_TIER} or {@link FILE_TIER}. */
42
+ tier: number
43
+ /** A done or cancelled issue: offered, after an open one on an equal match. */
44
+ closed?: boolean
45
+ /**
46
+ * An archived file, or an issue in an archived project: offered at the lowest
47
+ * priority — after every row that is not, on an equal match (Miky, 2026-10-03).
48
+ */
49
+ archived?: boolean
50
+ /** When it was written or last read, in seconds — newer first within a tier. */
51
+ at?: number
52
+ }
53
+
54
+ /** Where a message sits relative to the box you are writing in. */
55
+ export const MESSAGE_TIER = { here: 0, parent: 1 } as const
56
+
57
+ /** Where a file sits relative to you. `search` only ever comes from typing. */
58
+ export const FILE_TIER = { folder: 0, recent: 1, search: 2 } as const
59
+
60
+ /** How many rows each section shows (Miky, 2026-10-03): the box stays at the old list's height. */
61
+ export const REFERENCE_CAPS = { messages: 4, files: 6 } as const
62
+
63
+ export interface RankedReferences {
64
+ messages: ReferenceCandidate[]
65
+ files: ReferenceCandidate[]
66
+ }
67
+
68
+ export interface RankReferencesInput {
69
+ messages: readonly ReferenceCandidate[]
70
+ files: readonly ReferenceCandidate[]
71
+ /** What was typed after `[`. */
72
+ query: string
73
+ /** The kinds the app itself writes — the last tie-breaker. */
74
+ ownKinds?: readonly number[]
75
+ caps?: { messages: number; files: number }
76
+ /**
77
+ * Files never offered, by address: the file you are writing in, whose
78
+ * messages already lead Messages (Miky, 2026-10-03).
79
+ */
80
+ exclude?: readonly string[]
81
+ }
82
+
83
+ const normalize = (text: string) => text.toLowerCase().replace(/\s+/g, ' ').trim()
84
+
85
+ const isWordStart = (text: string, at: number) => at === 0 || !/[\p{L}\p{N}]/u.test(text[at - 1]!)
86
+
87
+ /**
88
+ * How well `text` holds `query`: 4 the whole of it, 3 its start, 2 the start of
89
+ * a word, 1 anywhere — or every word of the query at a word's start. 0 is no
90
+ * match. Case and runs of spaces are ignored.
91
+ */
92
+ export function referenceMatch(text: string, query: string): number {
93
+ const t = normalize(text)
94
+ const q = normalize(query)
95
+ if (!q) return 0
96
+ if (t === q) return 4
97
+ if (t.startsWith(q)) return 3
98
+ let at = t.indexOf(q)
99
+ if (at < 0) {
100
+ const words = q.split(' ')
101
+ if (words.length < 2) return 0
102
+ const starts = (w: string) => {
103
+ for (let i = t.indexOf(w); i >= 0; i = t.indexOf(w, i + 1)) if (isWordStart(t, i)) return true
104
+ return false
105
+ }
106
+ return words.every(starts) ? 1 : 0
107
+ }
108
+ for (; at >= 0; at = t.indexOf(q, at + 1)) if (isWordStart(t, at)) return 2
109
+ return 1
110
+ }
111
+
112
+ /** Keeps each id once, at its closest tier. */
113
+ function closest(candidates: readonly ReferenceCandidate[]): ReferenceCandidate[] {
114
+ const best = new Map<string, ReferenceCandidate>()
115
+ for (const c of candidates) {
116
+ const known = best.get(c.id)
117
+ if (!known || c.tier < known.tier) best.set(c.id, c)
118
+ }
119
+ return [...best.values()]
120
+ }
121
+
122
+ const newer = (a: ReferenceCandidate, b: ReferenceCandidate) => (b.at ?? 0) - (a.at ?? 0)
123
+
124
+ /**
125
+ * The two sections `[` draws, each ranked and capped.
126
+ *
127
+ * Nothing in the `search` tier is offered with nothing typed, nor anything that
128
+ * does not match what was typed. Ties end on recency, then the title, so the
129
+ * list holds still between keystrokes.
130
+ */
131
+ export function rankReferences({ messages, files, query, ownKinds = [], caps = REFERENCE_CAPS, exclude = [] }: RankReferencesInput): RankedReferences {
132
+ const typed = normalize(query) !== ''
133
+ const own = new Set(ownKinds)
134
+ const excluded = new Set(exclude)
135
+ const ownFirst = (a: ReferenceCandidate, b: ReferenceCandidate) => Number(!own.has(a.kind)) - Number(!own.has(b.kind))
136
+ const byTitle = (a: ReferenceCandidate, b: ReferenceCandidate) => a.title.localeCompare(b.title)
137
+
138
+ const messageScore = (m: ReferenceCandidate) => Math.max(referenceMatch(m.title, query), referenceMatch(m.search ?? m.caption, query))
139
+ const shownMessages = closest(messages)
140
+ .map((m) => ({ m, score: typed ? messageScore(m) : 0 }))
141
+ .filter(({ score }) => !typed || score > 0)
142
+ .sort((a, b) => b.score - a.score || a.m.tier - b.m.tier || newer(a.m, b.m) || a.m.id.localeCompare(b.m.id))
143
+ .slice(0, caps.messages)
144
+ .map(({ m }) => m)
145
+
146
+ const shownFiles = closest(files)
147
+ .filter((f) => !excluded.has(f.id) && (typed || f.tier !== FILE_TIER.search))
148
+ .map((f) => ({ f, score: typed ? referenceMatch(f.title, query) : 0 }))
149
+ .filter(({ score }) => !typed || score > 0)
150
+ .sort(
151
+ (a, b) =>
152
+ b.score - a.score ||
153
+ Number(!!a.f.archived) - Number(!!b.f.archived) ||
154
+ (typed ? Number(!!a.f.closed) - Number(!!b.f.closed) || a.f.tier - b.f.tier : a.f.tier - b.f.tier || Number(!!a.f.closed) - Number(!!b.f.closed)) ||
155
+ ownFirst(a.f, b.f) ||
156
+ newer(a.f, b.f) ||
157
+ byTitle(a.f, b.f),
158
+ )
159
+ .slice(0, caps.files)
160
+ .map(({ f }) => f)
161
+
162
+ return { messages: shownMessages, files: shownFiles }
163
+ }
164
+
165
+ /**
166
+ * A file as the body references it: `nostr:naddr…` with no relay hint, the
167
+ * same bytes a pasted link resolves to — so it earns its `["a", <address>]`
168
+ * through `referenceTagsFor` and draws as the same widget (SPEC §13.1). The
169
+ * title is never in the body: a file from a private Folder named in a wider
170
+ * one leaks nothing but its pointer.
171
+ *
172
+ * `address` is `kind:pubkey:d`; anything else throws.
173
+ */
174
+ export function fileReference(address: string): string {
175
+ return `nostr:${addrToNaddr(address)}`
176
+ }
177
+
178
+ /** What a {@link referenceSearch} asks the relay for: the files whose title holds `query`. */
179
+ export type ReferenceSearchFn = (query: string) => Promise<readonly ReferenceCandidate[]>
180
+
181
+ // The package targets no runtime's lib, and a pause is all it needs of one.
182
+ const timers = globalThis as unknown as { setTimeout(run: () => void, ms: number): unknown; clearTimeout(id: unknown): void }
183
+
184
+ export interface ReferenceSearch {
185
+ /**
186
+ * The search tier for `query`: what the relay last answered for it, or —
187
+ * while it is asked — for the longest query before it that it answered.
188
+ * Asks it, after a pause, when it has not been asked.
189
+ */
190
+ hits(query: string): readonly ReferenceCandidate[]
191
+ /** Called when an answer lands; returns the unsubscribe. */
192
+ subscribe(listener: () => void): () => void
193
+ /**
194
+ * Drops what is pending and what was answered. Call it when the signed-in
195
+ * person changes: answers are kept by the text asked, not by who asked, and
196
+ * the last person's hits name files the next one may not be able to read.
197
+ */
198
+ reset(): void
199
+ }
200
+
201
+ export interface ReferenceSearchOptions {
202
+ search: ReferenceSearchFn
203
+ /** The pause after a keystroke before asking. Default 200ms. */
204
+ delayMs?: number
205
+ /** How long a failed query answers no hits before it may be asked again. Default 5s. */
206
+ retryMs?: number
207
+ /** Shorter queries ask nothing. Default 2. */
208
+ minLength?: number
209
+ }
210
+
211
+ /**
212
+ * The third Files tier, as the list asks for it on every keystroke: answers
213
+ * now from what it holds, and asks the relay behind it.
214
+ *
215
+ * The rows already on screen never wait for the relay: a slow or failing
216
+ * search leaves them as they are, with no spinner and no error row
217
+ * (PEE-21). A failure answers no hits for `retryMs`, so a rate limit is not
218
+ * hammered on every render, and is then forgotten, so one blip does not hide
219
+ * that query for the rest of the session. Answers are filtered again by
220
+ * {@link rankReferences}, so a shorter query's hits shown meanwhile never
221
+ * offer a row the typed text does not match.
222
+ *
223
+ * Only the pause is cancelled by the next keystroke: a query already asked
224
+ * keeps its answer, which is still true of that query.
225
+ */
226
+ export function referenceSearch({ search, delayMs = 200, retryMs = 5000, minLength = 2 }: ReferenceSearchOptions): ReferenceSearch {
227
+ const answered = new Map<string, readonly ReferenceCandidate[]>()
228
+ const asking = new Set<string>()
229
+ const listeners = new Set<() => void>()
230
+ let paused: { query: string; timer: unknown } | null = null
231
+
232
+ const cancel = () => {
233
+ if (paused) timers.clearTimeout(paused.timer)
234
+ paused = null
235
+ }
236
+
237
+ const ask = (query: string) => {
238
+ cancel()
239
+ const timer = timers.setTimeout(() => {
240
+ paused = null
241
+ asking.add(query)
242
+ search(query)
243
+ .then(
244
+ (found) => found,
245
+ () => {
246
+ const failed: readonly ReferenceCandidate[] = []
247
+ timers.setTimeout(() => {
248
+ if (answered.get(query) === failed) answered.delete(query)
249
+ }, retryMs)
250
+ return failed
251
+ },
252
+ )
253
+ .then((found) => {
254
+ if (!asking.delete(query)) return
255
+ answered.set(query, found.length ? found.map((f) => ({ ...f, tier: FILE_TIER.search })) : found)
256
+ // A session's worth of queries; the oldest goes first.
257
+ if (answered.size > 64) answered.delete(answered.keys().next().value!)
258
+ for (const listener of listeners) listener()
259
+ })
260
+ }, delayMs)
261
+ paused = { query, timer }
262
+ }
263
+
264
+ return {
265
+ hits(raw) {
266
+ const query = normalize(raw)
267
+ if (query.length < minLength) {
268
+ cancel()
269
+ return []
270
+ }
271
+ const known = answered.get(query)
272
+ if (known) return known
273
+ if (paused?.query !== query && !asking.has(query)) ask(query)
274
+ for (let n = query.length - 1; n >= minLength; n--) {
275
+ const shorter = answered.get(query.slice(0, n).trim())
276
+ if (shorter) return shorter
277
+ }
278
+ return []
279
+ },
280
+ subscribe(listener) {
281
+ listeners.add(listener)
282
+ return () => listeners.delete(listener)
283
+ },
284
+ reset() {
285
+ cancel()
286
+ asking.clear()
287
+ answered.clear()
288
+ },
289
+ }
290
+ }