pups-client 0.3.0 → 0.5.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/README.md +37 -1
- package/dist/discovery.d.ts +5 -0
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +2 -0
- package/dist/discovery.js.map +1 -1
- package/dist/feed.d.ts +111 -5
- package/dist/feed.d.ts.map +1 -1
- package/dist/feed.js +186 -15
- package/dist/feed.js.map +1 -1
- package/dist/handles.d.ts +34 -0
- package/dist/handles.d.ts.map +1 -0
- package/dist/handles.js +91 -0
- package/dist/handles.js.map +1 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/mentions.d.ts +222 -0
- package/dist/mentions.d.ts.map +1 -0
- package/dist/mentions.js +341 -0
- package/dist/mentions.js.map +1 -0
- package/dist/session.d.ts +6 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +9 -0
- package/dist/session.js.map +1 -1
- package/dist/util.d.ts +2 -0
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js +2 -0
- package/dist/util.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/discovery.ts +7 -0
- package/src/feed.ts +238 -19
- package/src/handles.ts +101 -0
- package/src/index.ts +8 -1
- package/src/mentions.ts +443 -0
- package/src/session.ts +10 -0
- package/src/util.ts +4 -0
- package/src/version.ts +1 -1
package/src/feed.ts
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
import { isPupsError, PupsError } from './errors.js'
|
|
2
2
|
import { fileTypes } from './file-types.js'
|
|
3
3
|
import { pathFromPublicUrl } from './paths.js'
|
|
4
|
+
import { itemHandles } from './handles.js'
|
|
5
|
+
import type { Mentions, MentionReport, MentionSource, PlannedMention, Submission } from './mentions.js'
|
|
4
6
|
import type { Scope } from './scopes.js'
|
|
5
7
|
import type { Body, PupsSession } from './session.js'
|
|
6
|
-
import { randomString } from './util.js'
|
|
8
|
+
import { isObject, randomString } from './util.js'
|
|
7
9
|
|
|
8
10
|
/** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
|
|
9
11
|
export const FEED_REL = 'https://bigwide.net/ns/feed'
|
|
10
12
|
|
|
13
|
+
/**
|
|
14
|
+
* The site property in `host-meta.json` with the URL template of the pages that show single posts, e.g.
|
|
15
|
+
* `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs", RFC-7 "Post URLs").
|
|
16
|
+
*/
|
|
17
|
+
export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template'
|
|
18
|
+
|
|
11
19
|
/** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
|
|
12
20
|
export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md'
|
|
13
21
|
|
|
14
22
|
const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md'
|
|
23
|
+
const RFC4_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-4-Feed-Submissions.md'
|
|
15
24
|
const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1'
|
|
16
25
|
const FEED_CONTENT_TYPE = 'application/feed+json'
|
|
17
26
|
const maxArchiveNumber = 999_999
|
|
@@ -125,6 +134,26 @@ export interface FeedSettings {
|
|
|
125
134
|
[extension: `_${string}`]: unknown
|
|
126
135
|
}
|
|
127
136
|
|
|
137
|
+
/**
|
|
138
|
+
* The rules for comments of RFC-4 "Policies". Missing rules have RFC-4's defaults; servers may add others. The PUPS
|
|
139
|
+
* server's receiver enforces `title`, `minLength`, `maxLength`, `requireSocialSpec`, `allowEdit` and `allowDelete`.
|
|
140
|
+
*/
|
|
141
|
+
export interface CommentPolicy {
|
|
142
|
+
title?: 'required' | 'allowed' | 'none'
|
|
143
|
+
minLength?: number
|
|
144
|
+
maxLength?: number
|
|
145
|
+
requireSocialSpec?: boolean
|
|
146
|
+
allowEdit?: boolean
|
|
147
|
+
allowDelete?: boolean
|
|
148
|
+
[rule: string]: unknown
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Whether a feed accepts comments (RFC-4 `_submissions`): `pups` through the PUPS server's receiver, `other`
|
|
153
|
+
* through another service, such as an rssmention server, or `off`.
|
|
154
|
+
*/
|
|
155
|
+
export type CommentsState = 'pups' | 'other' | 'off'
|
|
156
|
+
|
|
128
157
|
/** Changes to the settings: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
|
|
129
158
|
export type FeedSettingsChanges = { [K in keyof FeedSettings]?: FeedSettings[K] | null }
|
|
130
159
|
|
|
@@ -183,6 +212,11 @@ export interface PostResult {
|
|
|
183
212
|
* as the `source` of an RFC-4 webmention. In a feed without archives, the feed file's URL plus `#<id>`.
|
|
184
213
|
*/
|
|
185
214
|
url: string
|
|
215
|
+
/**
|
|
216
|
+
* With the option `mentions`: the RFC-11 mentions, sent once the post is visible at its public URL. Never
|
|
217
|
+
* rejects. Missing if the post names and answers no one.
|
|
218
|
+
*/
|
|
219
|
+
mentions?: Promise<MentionReport[]>
|
|
186
220
|
}
|
|
187
221
|
|
|
188
222
|
export interface MediaResult {
|
|
@@ -222,6 +256,17 @@ export interface FeedOptions {
|
|
|
222
256
|
maxBytes?: number
|
|
223
257
|
/** How often an operation is repeated when another client changed the feed in between. Default 8. */
|
|
224
258
|
maxAttempts?: number
|
|
259
|
+
/**
|
|
260
|
+
* Whether posts of a feed with archives get a `url` from the site's post URL template, if `host-meta.json`
|
|
261
|
+
* declares one and the post has no `url` (RFC-7 "Post URLs"). Default true.
|
|
262
|
+
*/
|
|
263
|
+
postUrls?: boolean
|
|
264
|
+
/**
|
|
265
|
+
* Whether to send RFC-11 mentions after `addPost()`, `editPost()` and `deletePost()`: to the domains a post names
|
|
266
|
+
* (`@tim.example.com`) and to the author of the item it answers. `true` uses `session.mentions`. Default false.
|
|
267
|
+
* Each write can decide otherwise with its own option `mentions`, e.g. with the accounts the author confirmed.
|
|
268
|
+
*/
|
|
269
|
+
mentions?: boolean | Mentions
|
|
225
270
|
}
|
|
226
271
|
|
|
227
272
|
/** A feed registered in `host-meta.json`. */
|
|
@@ -235,6 +280,13 @@ export interface FeedLink {
|
|
|
235
280
|
|
|
236
281
|
type Signal = { signal?: AbortSignal }
|
|
237
282
|
|
|
283
|
+
/**
|
|
284
|
+
* Which RFC-11 mentions a write sends: `true` all of them, `false` none, or a list from `planMentions()`, e.g. the
|
|
285
|
+
* accounts the author confirmed. Default: the feed's option `mentions`.
|
|
286
|
+
*/
|
|
287
|
+
export type MentionChoice = boolean | PlannedMention[]
|
|
288
|
+
type WithMentions = Signal & { mentions?: MentionChoice }
|
|
289
|
+
|
|
238
290
|
interface Loaded {
|
|
239
291
|
path: string
|
|
240
292
|
doc: FeedDocument
|
|
@@ -262,8 +314,6 @@ function feedPaths(name?: string): { path: `/${string}`; directory: `/${string}`
|
|
|
262
314
|
return { path: `/feed/${name}.json`, directory: `/feed/${name}/` }
|
|
263
315
|
}
|
|
264
316
|
|
|
265
|
-
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
266
|
-
!!value && typeof value == 'object' && !Array.isArray(value)
|
|
267
317
|
|
|
268
318
|
const isFeedDocument = (value: unknown): value is FeedDocument =>
|
|
269
319
|
isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
|
|
@@ -301,6 +351,16 @@ export function itemIndex(item: FeedItem): number | undefined {
|
|
|
301
351
|
|
|
302
352
|
const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _pups: { ...isObject(item._pups) ? item._pups : {}, index } })
|
|
303
353
|
|
|
354
|
+
/** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
|
|
355
|
+
function validTemplate(template: unknown): template is string {
|
|
356
|
+
if (typeof template != 'string' || !/\{(index|id)\}/.test(template)) return false
|
|
357
|
+
try {
|
|
358
|
+
return new URL(template.replace(/\{(feed|index|id)\}/g, 'x')).protocol == 'https:'
|
|
359
|
+
} catch {
|
|
360
|
+
return false
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
304
364
|
/** The counter `_pups.next_index` of a file, if it has a valid one. */
|
|
305
365
|
function counterOf(doc: FeedDocument): number | undefined {
|
|
306
366
|
const next = doc._pups?.next_index
|
|
@@ -364,6 +424,9 @@ export class PupsFeed {
|
|
|
364
424
|
readonly #archivesWanted: boolean
|
|
365
425
|
readonly #maxBytes?: number
|
|
366
426
|
readonly #maxAttempts: number
|
|
427
|
+
readonly #postUrls: boolean
|
|
428
|
+
readonly #mentions?: Mentions
|
|
429
|
+
#template?: Promise<string | undefined>
|
|
367
430
|
|
|
368
431
|
/** @internal Use `session.feed()`. */
|
|
369
432
|
constructor(session: PupsSession, name?: string, options: FeedOptions = {}) {
|
|
@@ -377,6 +440,8 @@ export class PupsFeed {
|
|
|
377
440
|
this.#archivesWanted = options.startArchives ?? true
|
|
378
441
|
this.#maxBytes = options.maxBytes
|
|
379
442
|
this.#maxAttempts = options.maxAttempts ?? 8
|
|
443
|
+
this.#postUrls = options.postUrls ?? true
|
|
444
|
+
this.#mentions = options.mentions === true ? session.mentions : options.mentions || undefined
|
|
380
445
|
if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
|
|
381
446
|
throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.')
|
|
382
447
|
}
|
|
@@ -502,6 +567,52 @@ export class PupsFeed {
|
|
|
502
567
|
return this.#setImage('favicon', media, options.signal)
|
|
503
568
|
}
|
|
504
569
|
|
|
570
|
+
/** Whether the PUPS server can receive comments on the feed's posts (`comment_endpoint`, RFC-6 "Built-in receiver"). */
|
|
571
|
+
get commentsAvailable(): boolean {
|
|
572
|
+
return !!this.#session.server.commentEndpoint
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Whether the feed accepts comments, and through whom; `doc` is the feed file, e.g. from `load()`. */
|
|
576
|
+
comments(doc: FeedDocument): CommentsState {
|
|
577
|
+
const submissions = doc._submissions
|
|
578
|
+
if (!isObject(submissions)) return 'off'
|
|
579
|
+
const endpoint = this.#session.server.commentEndpoint
|
|
580
|
+
return endpoint && submissions.url == endpoint ? 'pups' : 'other'
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Lets readers comment on the feed's posts through the PUPS server, which puts the comments into the owner's inbox
|
|
585
|
+
* (RFC-6 "Built-in receiver"): writes RFC-4 `_submissions` into the feed file, with `comment_endpoint` as `url`,
|
|
586
|
+
* the comments policy (RFC-4's defaults for `title`, `minLength` and `maxLength`, overridden by `policy`) and
|
|
587
|
+
* `republish: "no"`. Replaces the `_submissions` of another service; check `comments()` first and ask the owner.
|
|
588
|
+
* Single posts are closed with `_commenting: { allowComments: false }` (RFC-4).
|
|
589
|
+
* @throws {PupsError} `unsupported` if the server has no `comment_endpoint`.
|
|
590
|
+
*/
|
|
591
|
+
async enableComments(settings: { policy?: CommentPolicy; tos?: string } = {}, options: Signal = {}): Promise<FeedDocument> {
|
|
592
|
+
const url = this.#session.server.commentEndpoint
|
|
593
|
+
if (!url) throw new PupsError('unsupported', 'This PUPS server doesn\'t receive comments: its configuration has no comment_endpoint (RFC-6, Built-in receiver).')
|
|
594
|
+
return this.#setSubmissions({
|
|
595
|
+
about: RFC4_URL,
|
|
596
|
+
url,
|
|
597
|
+
...settings.tos ? { tos: settings.tos } : {},
|
|
598
|
+
policies: { comments: { title: 'none', minLength: 2, maxLength: 2000, ...settings.policy } },
|
|
599
|
+
republish: 'no',
|
|
600
|
+
}, options.signal)
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Closes the feed for comments: removes `_submissions` from the feed file, whichever service it names. */
|
|
604
|
+
disableComments(options: Signal = {}): Promise<FeedDocument> {
|
|
605
|
+
return this.#setSubmissions(undefined, options.signal)
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
#setSubmissions(submissions: Record<string, unknown> | undefined, signal?: AbortSignal): Promise<FeedDocument> {
|
|
609
|
+
return this.#transaction(async () => {
|
|
610
|
+
const main = await this.#readControlled(this.path, signal)
|
|
611
|
+
const { _submissions: _old, ...doc } = main.doc
|
|
612
|
+
return this.#writeMain(submissions ? { ...doc, _submissions: submissions } : doc, main.etag, signal)
|
|
613
|
+
})
|
|
614
|
+
}
|
|
615
|
+
|
|
505
616
|
/**
|
|
506
617
|
* Uploads an image, audio or video file into the feed directory under a new, unique name, by default
|
|
507
618
|
* `images/<year>/…` for images and `media/<year>/…` for everything else. Reference it from a post by its `url`.
|
|
@@ -522,10 +633,15 @@ export class PupsFeed {
|
|
|
522
633
|
* holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
|
|
523
634
|
* archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
|
|
524
635
|
* media with `uploadMedia()` before posting.
|
|
636
|
+
* In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
|
|
637
|
+
* has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
|
|
638
|
+
* With the option `mentions`, the domains the post names and the author of the item it answers are notified
|
|
639
|
+
* (RFC-11) once the post is visible; see `PostResult.mentions`.
|
|
525
640
|
* @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
|
|
526
|
-
* archives, the feed file's URL plus `#<id>`, valid while the post is among the newest.
|
|
641
|
+
* archives, the feed file's URL plus `#<id>`, valid while the post is among the newest. The post's page, if it
|
|
642
|
+
* has one, is `item.url`.
|
|
527
643
|
*/
|
|
528
|
-
async addPost(input: PostInput, options:
|
|
644
|
+
async addPost(input: PostInput, options: WithMentions = {}): Promise<PostResult> {
|
|
529
645
|
const item = this.#newItem(input)
|
|
530
646
|
const signal = options.signal
|
|
531
647
|
let archiveUrl = ''
|
|
@@ -555,7 +671,8 @@ export class PupsFeed {
|
|
|
555
671
|
doc.items = started.items
|
|
556
672
|
}
|
|
557
673
|
}
|
|
558
|
-
const
|
|
674
|
+
const template = await this.#postUrlTemplate(signal)
|
|
675
|
+
const added = await this.#addToArchive(main, doc, item, signal, template)
|
|
559
676
|
archiveUrl = added.url
|
|
560
677
|
stored = added.item
|
|
561
678
|
doc._pups!.archive_url = added.url
|
|
@@ -568,7 +685,7 @@ export class PupsFeed {
|
|
|
568
685
|
doc.items = this.#newestItems(added.recent, doc.items, doc)
|
|
569
686
|
await this.#writeMain(doc, main.etag, signal)
|
|
570
687
|
})
|
|
571
|
-
return this.#result(stored, archiveUrl)
|
|
688
|
+
return this.#withMentions(options.mentions, this.#result(stored, archiveUrl), archiveUrl, stored, undefined, item => !!item)
|
|
572
689
|
}
|
|
573
690
|
|
|
574
691
|
/**
|
|
@@ -625,12 +742,16 @@ export class PupsFeed {
|
|
|
625
742
|
* a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
|
|
626
743
|
* function may run more than once.
|
|
627
744
|
*
|
|
628
|
-
* Apps should edit posts only when the owner asks them to, whichever app created them.
|
|
745
|
+
* Apps should edit posts only when the owner asks them to, whichever app created them. With the option
|
|
746
|
+
* `mentions`, everyone the old or the new version mentions is notified. A post of a feed with
|
|
747
|
+
* archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
|
|
629
748
|
* @throws {PupsError} `not_found`
|
|
630
749
|
*/
|
|
631
|
-
async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options:
|
|
750
|
+
async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: WithMentions = {}): Promise<PostResult> {
|
|
632
751
|
const signal = options.signal
|
|
633
|
-
|
|
752
|
+
let edit: { old: FeedItem; item: FeedItem; fileUrl: string } | undefined
|
|
753
|
+
const result = await this.#transaction(async () => {
|
|
754
|
+
edit = undefined
|
|
634
755
|
const { main, file, index } = await this.#findWritable(id, signal)
|
|
635
756
|
const old = file.doc.items[index]!
|
|
636
757
|
const fileUrl = this.#session.publicUrl(file.path)
|
|
@@ -640,11 +761,17 @@ export class PupsFeed {
|
|
|
640
761
|
let item: FeedItem = { ...changed, id, date_modified: now() }
|
|
641
762
|
// The index never changes (RFC-7 "Indexes").
|
|
642
763
|
if (oldIndex !== undefined) item = withIndex(item, oldIndex)
|
|
764
|
+
// A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
|
|
765
|
+
if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._pups?.archive_url) !== undefined)
|
|
766
|
+
item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal))
|
|
643
767
|
if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
|
|
644
768
|
const mainIndex = main.doc.items.findIndex(i => i.id == id)
|
|
645
769
|
if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
|
|
770
|
+
edit = { old, item, fileUrl }
|
|
646
771
|
return this.#result(item, fileUrl)
|
|
647
772
|
})
|
|
773
|
+
const done = edit as typeof edit
|
|
774
|
+
return done ? this.#withMentions(options.mentions, result, done.fileUrl, done.item, done.old, found => found?.date_modified == done.item.date_modified) : result
|
|
648
775
|
}
|
|
649
776
|
|
|
650
777
|
/**
|
|
@@ -654,10 +781,12 @@ export class PupsFeed {
|
|
|
654
781
|
* @returns the deleted item, and the public URLs of the deleted media files.
|
|
655
782
|
* @throws {PupsError} `not_found`
|
|
656
783
|
*/
|
|
657
|
-
async deletePost(id: string, options:
|
|
784
|
+
async deletePost(id: string, options: WithMentions & { deleteMedia?: boolean } = {}): Promise<{ item: FeedItem; deletedMedia: string[]; mentions?: Promise<MentionReport[]> }> {
|
|
658
785
|
const signal = options.signal
|
|
786
|
+
let fileUrl = ''
|
|
659
787
|
const item = await this.#transaction(async () => {
|
|
660
788
|
const { main, file, index } = await this.#findWritable(id, signal)
|
|
789
|
+
fileUrl = this.#session.publicUrl(file.path)
|
|
661
790
|
const item = file.doc.items[index]!
|
|
662
791
|
if (file != main) {
|
|
663
792
|
await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal)
|
|
@@ -683,7 +812,77 @@ export class PupsFeed {
|
|
|
683
812
|
if (path && await this.#deleteQuietly(path, signal)) deletedMedia.push(url)
|
|
684
813
|
}
|
|
685
814
|
}
|
|
686
|
-
|
|
815
|
+
const mentions = this.#sendMentions(options.mentions, fileUrl, undefined, item, found => !found)
|
|
816
|
+
return { item, deletedMedia, ...mentions ? { mentions } : {} }
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Sends the RFC-11 mentions of a post now, e.g. to try again those that failed (see `Mentions.notifyAll()`). With
|
|
821
|
+
* `previous`, the version before an edit, also to the accounts that one mentioned.
|
|
822
|
+
* @throws {PupsError} `not_found`
|
|
823
|
+
*/
|
|
824
|
+
async sendMentions(id: string, options: Signal & { previous?: FeedItem } = {}): Promise<MentionReport[]> {
|
|
825
|
+
const post = await this.getPost(id, options)
|
|
826
|
+
if (!post) throw new PupsError('not_found', `The feed has no post with the id "${id}".`)
|
|
827
|
+
return this.#mentionSender.notifyAll({ source: post.url, item: post.item, previous: options.previous, me: this.#session.me }, options)
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Submits a post that answers an item of an RFC-4 feed, e.g. a comment, to that feed's `_submissions.url`
|
|
832
|
+
* (RFC-4 "Submitting"): `source` is the post's archive URL plus `#<id>`, `target` its `_source.inReplyTo`. Call it
|
|
833
|
+
* after `addPost()` or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service
|
|
834
|
+
* and what its `republish` means before the first submission.
|
|
835
|
+
* @throws {PupsError} `not_found`; `invalid_request` if the post answers nothing; `unsupported` if the target
|
|
836
|
+
* feed takes no submissions.
|
|
837
|
+
*/
|
|
838
|
+
async submit(id: string, options: Signal = {}): Promise<Submission> {
|
|
839
|
+
const post = await this.getPost(id, options)
|
|
840
|
+
if (!post) throw new PupsError('not_found', `The feed has no post with the id "${id}".`)
|
|
841
|
+
const source = isObject(post.item._source) ? post.item._source : {}
|
|
842
|
+
if (typeof source.inReplyTo != 'string') throw new PupsError('invalid_request', `The post "${id}" has no _source.inReplyTo, so it answers nothing (RFC-4).`)
|
|
843
|
+
return this.#session.mentions.submit(post.url, source.inReplyTo, options)
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* The RFC-11 mentions a post would send (see `Mentions.plan()`), e.g. to ask the author before posting:
|
|
848
|
+
*
|
|
849
|
+
* ```ts
|
|
850
|
+
* const planned = await feed.planMentions(input)
|
|
851
|
+
* const confirmed = planned.length && await askToNotify(planned) ? planned : false // the app's dialog
|
|
852
|
+
* await feed.addPost(input, { mentions: confirmed })
|
|
853
|
+
* ```
|
|
854
|
+
*
|
|
855
|
+
* For an edit, pass the post as it will be and the current version as `previous`; for a delete, only `previous`.
|
|
856
|
+
*/
|
|
857
|
+
planMentions(post: MentionSource | undefined, options: Signal & { previous?: MentionSource; discover?: boolean } = {}): Promise<PlannedMention[]> {
|
|
858
|
+
return this.#mentionSender.plan({ item: post, previous: options.previous, me: this.#session.me }, options)
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
get #mentionSender(): Mentions {
|
|
862
|
+
return this.#mentions ?? this.#session.mentions
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** The result with the RFC-11 mentions of the post, if the write sends them (see `#sendMentions()`). */
|
|
866
|
+
#withMentions(choice: MentionChoice | undefined, result: PostResult, fileUrl: string, item: FeedItem, previous: FeedItem | undefined, ready: (item?: FeedItem) => boolean): PostResult {
|
|
867
|
+
const mentions = this.#sendMentions(choice, fileUrl, item, previous, ready)
|
|
868
|
+
return mentions ? { ...result, mentions } : result
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Sends the RFC-11 mentions of a post in the background, once its file at `fileUrl` is in the state `ready` wants:
|
|
873
|
+
* all, none, or the planned ones, as `choice` (default: the feed's option) says. Undefined if nothing is sent.
|
|
874
|
+
*/
|
|
875
|
+
#sendMentions(choice: MentionChoice | undefined, fileUrl: string, item: FeedItem | undefined, previous: FeedItem | undefined, ready: (item?: FeedItem) => boolean): Promise<MentionReport[]> | undefined {
|
|
876
|
+
choice ??= !!this.#mentions
|
|
877
|
+
const relevant = (i?: FeedItem) => !!i && (itemHandles(i).length > 0 || (isObject(i._source) && typeof i._source.inReplyTo == 'string'))
|
|
878
|
+
if (Array.isArray(choice) ? !choice.length : !choice || !(relevant(item) || relevant(previous))) return
|
|
879
|
+
const mentions = this.#mentionSender
|
|
880
|
+
const id = (item ?? previous)!.id
|
|
881
|
+
const source = `${fileUrl}#${encodeURIComponent(id)}`
|
|
882
|
+
return (async () => {
|
|
883
|
+
await mentions.waitForItem(fileUrl, id, ready)
|
|
884
|
+
return Array.isArray(choice) ? mentions.sendPlanned(source, choice) : mentions.notifyAll({ source, item, previous, me: this.#session.me })
|
|
885
|
+
})().catch(() => [])
|
|
687
886
|
}
|
|
688
887
|
|
|
689
888
|
// Reading
|
|
@@ -830,9 +1029,12 @@ export class PupsFeed {
|
|
|
830
1029
|
return match ? Number(match[1]) : undefined
|
|
831
1030
|
}
|
|
832
1031
|
|
|
833
|
-
/**
|
|
1032
|
+
/**
|
|
1033
|
+
* A new archive with the feed fields of the feed file (RFC-7 "Archives"), except `_submissions`: whether a feed
|
|
1034
|
+
* accepts comments is said by its feed file alone.
|
|
1035
|
+
*/
|
|
834
1036
|
#newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, nextIndex?: number): FeedDocument {
|
|
835
|
-
const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main
|
|
1037
|
+
const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, _submissions: _s, ...fields } = main
|
|
836
1038
|
const { archive_url: _archive, next_index: _counter, ...marker } = _pups ?? {}
|
|
837
1039
|
const podcast = fields._podcast
|
|
838
1040
|
if (isObject(podcast) && 'liveItems' in podcast) {
|
|
@@ -940,7 +1142,8 @@ export class PupsFeed {
|
|
|
940
1142
|
* indexed first, and the post then starts again.
|
|
941
1143
|
* @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
|
|
942
1144
|
*/
|
|
943
|
-
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
|
|
1145
|
+
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal, template?: string): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
|
|
1146
|
+
const place = (index: number) => this.#withPostUrl(withIndex(item, index), index, template)
|
|
944
1147
|
const newest = this.#archiveNumber(doc._pups?.archive_url)
|
|
945
1148
|
let previous: FeedItem[] = []
|
|
946
1149
|
// The index for the item if it goes into a new archive.
|
|
@@ -951,7 +1154,7 @@ export class PupsFeed {
|
|
|
951
1154
|
// The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
|
|
952
1155
|
const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined
|
|
953
1156
|
if (before && before != 'foreign') next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc))
|
|
954
|
-
const stored =
|
|
1157
|
+
const stored = place(next)
|
|
955
1158
|
await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1)
|
|
956
1159
|
return { url: this.#archiveUrl(newest), recent: [stored], item: stored }
|
|
957
1160
|
}
|
|
@@ -963,7 +1166,7 @@ export class PupsFeed {
|
|
|
963
1166
|
// Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
|
|
964
1167
|
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)))
|
|
965
1168
|
const copy = indexed.items.find(i => i.id == item.id)
|
|
966
|
-
const stored =
|
|
1169
|
+
const stored = place(copy ? itemIndex(copy)! : indexed.next)
|
|
967
1170
|
const merged = mergeItems(indexed.items, [stored])
|
|
968
1171
|
if (merged.length <= this.#archiveSize) {
|
|
969
1172
|
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
|
|
@@ -977,7 +1180,7 @@ export class PupsFeed {
|
|
|
977
1180
|
// The archive before the new one: the newest, or for a feed without archives the end of its old chain.
|
|
978
1181
|
const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest)
|
|
979
1182
|
for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
|
|
980
|
-
const stored =
|
|
1183
|
+
const stored = place(next)
|
|
981
1184
|
try {
|
|
982
1185
|
await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1)
|
|
983
1186
|
return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored }
|
|
@@ -989,7 +1192,7 @@ export class PupsFeed {
|
|
|
989
1192
|
if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
|
|
990
1193
|
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next))
|
|
991
1194
|
const copy = indexed.items.find(i => i.id == item.id)
|
|
992
|
-
const added =
|
|
1195
|
+
const added = place(copy ? itemIndex(copy)! : indexed.next)
|
|
993
1196
|
const merged = mergeItems(indexed.items, [added])
|
|
994
1197
|
if (merged.length <= this.#archiveSize) {
|
|
995
1198
|
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
|
|
@@ -1004,6 +1207,22 @@ export class PupsFeed {
|
|
|
1004
1207
|
|
|
1005
1208
|
// Items and media
|
|
1006
1209
|
|
|
1210
|
+
/** The site's post URL template from `host-meta.json`, read once; undefined if there is none or it can't be read. */
|
|
1211
|
+
#postUrlTemplate(signal?: AbortSignal): Promise<string | undefined> {
|
|
1212
|
+
if (!this.#postUrls) return Promise.resolve(undefined)
|
|
1213
|
+
this.#template ??= this.#session.hostMeta.get({ signal })
|
|
1214
|
+
.then(doc => doc.properties?.[POST_URL_TEMPLATE])
|
|
1215
|
+
.then(template => validTemplate(template) ? template : undefined, () => undefined)
|
|
1216
|
+
return this.#template
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/** The item with the `url` from the post URL template (RFC-7 "Post URLs"), unless it has one. */
|
|
1220
|
+
#withPostUrl(item: FeedItem, index: number, template?: string): FeedItem {
|
|
1221
|
+
if (!template || item.url) return item
|
|
1222
|
+
const vars: Record<string, string> = { feed: this.path.slice(1, -'.json'.length), index: String(index), id: encodeURIComponent(item.id) }
|
|
1223
|
+
return { ...item, url: template.replace(/\{(feed|index|id)\}/g, (_, name: string) => vars[name]!) }
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1007
1226
|
#newItem(input: PostInput): FeedItem {
|
|
1008
1227
|
const { id, markdown, date_published, ...fields } = input
|
|
1009
1228
|
if (id !== undefined && (typeof id != 'string' || !id))
|
package/src/handles.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Handles in text (bigwide.net RFC-11 "Handles"): `@` followed by a host name with at least two labels, e.g.
|
|
3
|
+
* `@tim.example.com`. Not e-mail addresses (`tim@tim.example.com`), fediverse addresses (`@tim@social.example`),
|
|
4
|
+
* names without a dot (`@foobar`) or paths (`@x.example/path`). A `/` directly between handles separates them:
|
|
5
|
+
* `@a.example/@b.example` names both.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const LABEL = '[\\p{L}\\p{N}](?:[\\p{L}\\p{M}\\p{N}-]*[\\p{L}\\p{M}\\p{N}])?'
|
|
9
|
+
const HOST = `(?:${LABEL}\\.)+\\p{L}(?:[\\p{L}\\p{M}\\p{N}-]*[\\p{L}\\p{M}\\p{N}])?`
|
|
10
|
+
/** A handle, or several separated by `/`, with RFC-11's rules for the characters before and after. */
|
|
11
|
+
const HANDLES_RE = new RegExp(
|
|
12
|
+
`(?:^|(?<=[\\s\\p{P}\\p{S}]))(?<![._\\-+/@])@${HOST}(?:/@${HOST})*(?![\\p{L}\\p{M}\\p{N}_\\-/@]|\\.[\\p{L}\\p{N}])`, 'gu')
|
|
13
|
+
|
|
14
|
+
/** Elements whose content is never shown. */
|
|
15
|
+
const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'noscript', 'iframe', 'object', 'embed', 'svg', 'math', 'head', 'title', 'select', 'textarea', 'button'])
|
|
16
|
+
/** Elements whose content doesn't count for handles. */
|
|
17
|
+
const CODE_TAGS = new Set(['code', 'pre'])
|
|
18
|
+
const BLOCK_TAGS = new Set(['address', 'article', 'aside', 'blockquote', 'br', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 'footer',
|
|
19
|
+
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'li', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'td', 'th', 'tr', 'ul'])
|
|
20
|
+
const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr'])
|
|
21
|
+
const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: ' ', commat: '@', sol: '/', period: '.' }
|
|
22
|
+
|
|
23
|
+
/** A host name as handles are compared: lowercase ASCII (IDNA). Undefined if it isn't a valid host. */
|
|
24
|
+
export function asciiHost(host: string): string | undefined {
|
|
25
|
+
try {
|
|
26
|
+
const url = new URL(`https://${host}/`)
|
|
27
|
+
return url.hostname && url.pathname == '/' && !url.port ? url.hostname.toLowerCase() : undefined
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The host of an account like `@alice.example.com`, in comparable form, or undefined. */
|
|
34
|
+
export function accountHost(account: unknown): string | undefined {
|
|
35
|
+
const match = typeof account == 'string' ? /^@([^@\s/]+)$/u.exec(account.trim()) : null
|
|
36
|
+
return match ? asciiHost(match[1]!) : undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The hosts of all handles in a plain text, in comparable form and in order, each once. */
|
|
40
|
+
export function findHandles(text: string): string[] {
|
|
41
|
+
const hosts = [...text.matchAll(HANDLES_RE)].flatMap(m => m[0].split('/').map(h => asciiHost(h.slice(1))))
|
|
42
|
+
return [...new Set(hosts.filter((h): h is string => !!h))]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const decode = (text: string) => text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name: string) => {
|
|
46
|
+
if (name[0] != '#') return ENTITIES[name.toLowerCase()] ?? entity
|
|
47
|
+
const code = name[1] == 'x' || name[1] == 'X' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10)
|
|
48
|
+
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The visible text of an HTML fragment, with whitespace collapsed: without attribute values, comments and the
|
|
53
|
+
* content of elements that are never shown. With `skipCode`, the content of `code` and `pre` is left out as well.
|
|
54
|
+
* A small tokenizer, so that it works without a DOM; good enough for finding handles, not a sanitizer.
|
|
55
|
+
*/
|
|
56
|
+
export function visibleText(html: string, skipCode = false): string {
|
|
57
|
+
let out = ''
|
|
58
|
+
const hidden: string[] = []
|
|
59
|
+
const tokens = /<!--[\s\S]*?(?:-->|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>|$)|<[!?][^>]*>?|<\/?([a-zA-Z][a-zA-Z0-9-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|[^<]+|</g
|
|
60
|
+
for (const [token, rawTag, attributes] of html.matchAll(tokens)) {
|
|
61
|
+
if (!rawTag) {
|
|
62
|
+
if (token[0] != '<' || token == '<') {
|
|
63
|
+
if (!hidden.length) out += decode(token)
|
|
64
|
+
}
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
const tag = rawTag.toLowerCase()
|
|
68
|
+
const closing = token[1] == '/'
|
|
69
|
+
if (BLOCK_TAGS.has(tag)) out += ' '
|
|
70
|
+
const hides = HIDDEN_TAGS.has(tag) || (skipCode && CODE_TAGS.has(tag))
|
|
71
|
+
if (!hides) continue
|
|
72
|
+
if (closing) {
|
|
73
|
+
const at = hidden.lastIndexOf(tag)
|
|
74
|
+
if (at >= 0) hidden.length = at
|
|
75
|
+
out += ' '
|
|
76
|
+
} else if (!VOID_TAGS.has(tag) && !attributes?.trimEnd().endsWith('/')) hidden.push(tag)
|
|
77
|
+
}
|
|
78
|
+
return out.replace(/\s+/g, ' ').trim()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The parts of a JSON Feed item in which RFC-11 finds handles. */
|
|
82
|
+
export interface HandleSource {
|
|
83
|
+
title?: unknown
|
|
84
|
+
content_html?: unknown
|
|
85
|
+
content_text?: unknown
|
|
86
|
+
/** The Markdown of a `PostInput`, which becomes `content_text` if there is no other content. */
|
|
87
|
+
markdown?: unknown
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The text of an item in which handles are found: the title, and the visible text of its HTML without code, or its
|
|
92
|
+
* plain text (for a `PostInput`, its Markdown).
|
|
93
|
+
*/
|
|
94
|
+
export function handleText(item: HandleSource): string {
|
|
95
|
+
const text = typeof item.content_text == 'string' ? item.content_text : typeof item.markdown == 'string' ? item.markdown : undefined
|
|
96
|
+
const body = typeof item.content_html == 'string' ? visibleText(item.content_html, true) : text?.replace(/\s+/g, ' ').trim() ?? ''
|
|
97
|
+
return `${typeof item.title == 'string' ? item.title : ''} ${body}`.trim()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The hosts of the handles in an item (RFC-11 "Finding handles in text"). */
|
|
101
|
+
export const itemHandles = (item: HandleSource) => findHandles(handleText(item))
|
package/src/index.ts
CHANGED
|
@@ -16,8 +16,10 @@ export type {
|
|
|
16
16
|
} from './client.js'
|
|
17
17
|
export { PupsSession } from './session.js'
|
|
18
18
|
export type { Body, JsonBody, SessionChangeEvent, StoredFile, WriteOptions, WriteResult } from './session.js'
|
|
19
|
-
export { FEED_REL, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
|
|
19
|
+
export { FEED_REL, POST_URL_TEMPLATE, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
|
|
20
20
|
export type {
|
|
21
|
+
CommentPolicy,
|
|
22
|
+
CommentsState,
|
|
21
23
|
FeedAttachment,
|
|
22
24
|
FeedAuthor,
|
|
23
25
|
FeedDocument,
|
|
@@ -29,6 +31,7 @@ export type {
|
|
|
29
31
|
FeedSetup,
|
|
30
32
|
FeedState,
|
|
31
33
|
ItemMarker,
|
|
34
|
+
MentionChoice,
|
|
32
35
|
MediaInput,
|
|
33
36
|
MediaResult,
|
|
34
37
|
PostChanges,
|
|
@@ -37,6 +40,10 @@ export type {
|
|
|
37
40
|
PupsMarker,
|
|
38
41
|
} from './feed.js'
|
|
39
42
|
export { HostMetaEditor } from './host-meta.js'
|
|
43
|
+
export { MENTION_REL, Mentions } from './mentions.js'
|
|
44
|
+
export type { Delivery, DeliveryStatus, FoundItem, MentionReport, MentionSource, MentionsOptions, PlannedMention, PostChange, PostMentions, Submission, SubmissionStatus } from './mentions.js'
|
|
45
|
+
export { accountHost, findHandles, handleText, itemHandles, visibleText } from './handles.js'
|
|
46
|
+
export type { HandleSource } from './handles.js'
|
|
40
47
|
export type { HostMetaDocument, HostMetaLink } from './host-meta.js'
|
|
41
48
|
export { PupsError, isPupsError } from './errors.js'
|
|
42
49
|
export type { PupsErrorCode } from './errors.js'
|