pups-client 0.2.0 → 0.4.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 +28 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/main.js.map +1 -1
- package/dist/discovery.d.ts +2 -0
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +1 -0
- package/dist/discovery.js.map +1 -1
- package/dist/feed.d.ts +39 -2
- package/dist/feed.d.ts.map +1 -1
- package/dist/feed.js +224 -40
- package/dist/feed.js.map +1 -1
- package/dist/host-meta.d.ts +22 -3
- package/dist/host-meta.d.ts.map +1 -1
- package/dist/host-meta.js +37 -5
- package/dist/host-meta.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/paths.d.ts +11 -1
- package/dist/paths.d.ts.map +1 -1
- package/dist/paths.js +17 -1
- package/dist/paths.js.map +1 -1
- package/dist/scopes.d.ts +15 -4
- package/dist/scopes.d.ts.map +1 -1
- package/dist/scopes.js +21 -9
- package/dist/scopes.js.map +1 -1
- package/dist/session.d.ts +39 -7
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +68 -15
- package/dist/session.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/cli/main.ts +4 -4
- package/src/discovery.ts +3 -0
- package/src/feed.ts +245 -41
- package/src/host-meta.ts +43 -7
- package/src/index.ts +2 -1
- package/src/paths.ts +19 -1
- package/src/scopes.ts +33 -11
- package/src/session.ts +75 -18
- package/src/version.ts +1 -1
package/src/feed.ts
CHANGED
|
@@ -8,6 +8,12 @@ import { randomString } from './util.js'
|
|
|
8
8
|
/** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
|
|
9
9
|
export const FEED_REL = 'https://bigwide.net/ns/feed'
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* The site property in `host-meta.json` with the URL template of the pages that show single posts, e.g.
|
|
13
|
+
* `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs", RFC-7 "Post URLs").
|
|
14
|
+
*/
|
|
15
|
+
export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template'
|
|
16
|
+
|
|
11
17
|
/** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
|
|
12
18
|
export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md'
|
|
13
19
|
|
|
@@ -64,6 +70,15 @@ export interface FeedItem {
|
|
|
64
70
|
tags?: string[]
|
|
65
71
|
language?: string
|
|
66
72
|
attachments?: FeedAttachment[]
|
|
73
|
+
/** The item's `_pups` object, with its index (RFC-7 "Indexes"). */
|
|
74
|
+
_pups?: ItemMarker
|
|
75
|
+
[field: string]: unknown
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The `_pups` object of an item. */
|
|
79
|
+
export interface ItemMarker {
|
|
80
|
+
/** The item's index: 0 for a feed's first item, then counting up; never changed, never used again (RFC-7 "Indexes"). */
|
|
81
|
+
index?: number
|
|
67
82
|
[field: string]: unknown
|
|
68
83
|
}
|
|
69
84
|
|
|
@@ -75,6 +90,11 @@ export interface PupsMarker {
|
|
|
75
90
|
archive_url?: string
|
|
76
91
|
/** In an archive: the public URL of the feed file, which readers poll. */
|
|
77
92
|
updates_url?: string
|
|
93
|
+
/**
|
|
94
|
+
* The index the next new item gets (RFC-7 "Indexes"). Valid in the newest archive, or in the feed file of a feed
|
|
95
|
+
* without archives.
|
|
96
|
+
*/
|
|
97
|
+
next_index?: number
|
|
78
98
|
[field: string]: unknown
|
|
79
99
|
}
|
|
80
100
|
|
|
@@ -160,6 +180,8 @@ export type PostChanges = { [K in Exclude<keyof PostInput, 'id'>]?: PostInput[K]
|
|
|
160
180
|
|
|
161
181
|
export interface PostResult {
|
|
162
182
|
id: string
|
|
183
|
+
/** The item's index (RFC-7 "Indexes"); undefined for an item that has none yet. */
|
|
184
|
+
index?: number
|
|
163
185
|
/** The item as stored. */
|
|
164
186
|
item: FeedItem
|
|
165
187
|
/**
|
|
@@ -206,6 +228,11 @@ export interface FeedOptions {
|
|
|
206
228
|
maxBytes?: number
|
|
207
229
|
/** How often an operation is repeated when another client changed the feed in between. Default 8. */
|
|
208
230
|
maxAttempts?: number
|
|
231
|
+
/**
|
|
232
|
+
* Whether posts of a feed with archives get a `url` from the site's post URL template, if `host-meta.json`
|
|
233
|
+
* declares one and the post has no `url` (RFC-7 "Post URLs"). Default true.
|
|
234
|
+
*/
|
|
235
|
+
postUrls?: boolean
|
|
209
236
|
}
|
|
210
237
|
|
|
211
238
|
/** A feed registered in `host-meta.json`. */
|
|
@@ -277,6 +304,50 @@ function mergeItems(existing: FeedItem[], incoming: FeedItem[]): FeedItem[] {
|
|
|
277
304
|
return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)]
|
|
278
305
|
}
|
|
279
306
|
|
|
307
|
+
/** The index of an item (RFC-7 "Indexes"), or undefined if it has none. */
|
|
308
|
+
export function itemIndex(item: FeedItem): number | undefined {
|
|
309
|
+
const index = isObject(item._pups) ? item._pups.index : undefined
|
|
310
|
+
return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _pups: { ...isObject(item._pups) ? item._pups : {}, index } })
|
|
314
|
+
|
|
315
|
+
/** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
|
|
316
|
+
function validTemplate(template: unknown): template is string {
|
|
317
|
+
if (typeof template != 'string' || !/\{(index|id)\}/.test(template)) return false
|
|
318
|
+
try {
|
|
319
|
+
return new URL(template.replace(/\{(feed|index|id)\}/g, 'x')).protocol == 'https:'
|
|
320
|
+
} catch {
|
|
321
|
+
return false
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The counter `_pups.next_index` of a file, if it has a valid one. */
|
|
326
|
+
function counterOf(doc: FeedDocument): number | undefined {
|
|
327
|
+
const next = doc._pups?.next_index
|
|
328
|
+
return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** The next free index: above every index of `items`, and at least each of `counters`. */
|
|
332
|
+
const nextFree = (items: FeedItem[], ...counters: (number | undefined)[]) =>
|
|
333
|
+
Math.max(0, ...counters.filter((c): c is number => c !== undefined), ...items.map(item => (itemIndex(item) ?? -1) + 1))
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Gives the items without an index (newest first, as in a file) the next indexes from `next`, the oldest first
|
|
337
|
+
* (RFC-7 "Items without an index").
|
|
338
|
+
* @returns the items, and the counter after them.
|
|
339
|
+
*/
|
|
340
|
+
function indexItems(items: FeedItem[], next: number): { items: FeedItem[]; next: number; changed: boolean } {
|
|
341
|
+
const result = [...items]
|
|
342
|
+
let changed = false
|
|
343
|
+
for (let i = result.length - 1; i >= 0; i--)
|
|
344
|
+
if (itemIndex(result[i]!) === undefined) {
|
|
345
|
+
result[i] = withIndex(result[i]!, next++)
|
|
346
|
+
changed = true
|
|
347
|
+
}
|
|
348
|
+
return { items: result, next, changed }
|
|
349
|
+
}
|
|
350
|
+
|
|
280
351
|
/** Every string inside `value`, deeply. */
|
|
281
352
|
function* strings(value: unknown): Generator<string> {
|
|
282
353
|
if (typeof value == 'string') yield value
|
|
@@ -314,6 +385,8 @@ export class PupsFeed {
|
|
|
314
385
|
readonly #archivesWanted: boolean
|
|
315
386
|
readonly #maxBytes?: number
|
|
316
387
|
readonly #maxAttempts: number
|
|
388
|
+
readonly #postUrls: boolean
|
|
389
|
+
#template?: Promise<string | undefined>
|
|
317
390
|
|
|
318
391
|
/** @internal Use `session.feed()`. */
|
|
319
392
|
constructor(session: PupsSession, name?: string, options: FeedOptions = {}) {
|
|
@@ -327,6 +400,7 @@ export class PupsFeed {
|
|
|
327
400
|
this.#archivesWanted = options.startArchives ?? true
|
|
328
401
|
this.#maxBytes = options.maxBytes
|
|
329
402
|
this.#maxAttempts = options.maxAttempts ?? 8
|
|
403
|
+
this.#postUrls = options.postUrls ?? true
|
|
330
404
|
if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
|
|
331
405
|
throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.')
|
|
332
406
|
}
|
|
@@ -472,13 +546,17 @@ export class PupsFeed {
|
|
|
472
546
|
* holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
|
|
473
547
|
* archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
|
|
474
548
|
* media with `uploadMedia()` before posting.
|
|
549
|
+
* In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
|
|
550
|
+
* has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
|
|
475
551
|
* @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
|
|
476
|
-
* archives, the feed file's URL plus `#<id>`, valid while the post is among the newest.
|
|
552
|
+
* archives, the feed file's URL plus `#<id>`, valid while the post is among the newest. The post's page, if it
|
|
553
|
+
* has one, is `item.url`.
|
|
477
554
|
*/
|
|
478
555
|
async addPost(input: PostInput, options: Signal = {}): Promise<PostResult> {
|
|
479
556
|
const item = this.#newItem(input)
|
|
480
557
|
const signal = options.signal
|
|
481
558
|
let archiveUrl = ''
|
|
559
|
+
let stored = item
|
|
482
560
|
let firstAttempt = true
|
|
483
561
|
await this.#transaction(async () => {
|
|
484
562
|
const main = await this.#readControlled(this.path, signal)
|
|
@@ -489,24 +567,58 @@ export class PupsFeed {
|
|
|
489
567
|
const doc: FeedDocument = { ...main.doc, _pups: { ...main.doc._pups } }
|
|
490
568
|
const hasArchives = this.#archiveNumber(doc._pups!.archive_url) !== undefined
|
|
491
569
|
if (!hasArchives && !this.#archivesWanted) {
|
|
492
|
-
// A feed without archives: the feed file is all there is (RFC-7 "Posting").
|
|
570
|
+
// A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
|
|
493
571
|
archiveUrl = this.url
|
|
494
|
-
|
|
572
|
+
const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)))
|
|
573
|
+
stored = withIndex(item, indexed.next)
|
|
574
|
+
doc._pups!.next_index = indexed.next + 1
|
|
575
|
+
await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal)
|
|
495
576
|
return
|
|
496
577
|
}
|
|
497
578
|
if (!hasArchives) {
|
|
498
579
|
const started = await this.#startArchives(main, signal)
|
|
499
|
-
if (started)
|
|
580
|
+
if (started) {
|
|
581
|
+
doc._pups!.archive_url = started.url
|
|
582
|
+
doc.items = started.items
|
|
583
|
+
}
|
|
500
584
|
}
|
|
501
|
-
const
|
|
585
|
+
const template = await this.#postUrlTemplate(signal)
|
|
586
|
+
const added = await this.#addToArchive(main, doc, item, signal, template)
|
|
502
587
|
archiveUrl = added.url
|
|
588
|
+
stored = added.item
|
|
503
589
|
doc._pups!.archive_url = added.url
|
|
504
|
-
|
|
505
|
-
|
|
590
|
+
if (!hasArchives) {
|
|
591
|
+
// The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
|
|
592
|
+
// holds the counter.
|
|
593
|
+
delete doc.next_url
|
|
594
|
+
delete doc._pups!.next_index
|
|
595
|
+
}
|
|
506
596
|
doc.items = this.#newestItems(added.recent, doc.items, doc)
|
|
507
597
|
await this.#writeMain(doc, main.etag, signal)
|
|
508
598
|
})
|
|
509
|
-
return this.#result(
|
|
599
|
+
return this.#result(stored, archiveUrl)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Gives every item of the feed without an index one (RFC-7 "Indexing an existing feed"), and sets the counter.
|
|
604
|
+
* `addPost()` does this by itself before the first post to a feed that hasn't been indexed yet; call it to
|
|
605
|
+
* index a feed without posting.
|
|
606
|
+
*/
|
|
607
|
+
async assignIndexes(options: Signal = {}): Promise<void> {
|
|
608
|
+
const signal = options.signal
|
|
609
|
+
await this.#transaction(async () => {
|
|
610
|
+
const main = await this.#readControlled(this.path, signal)
|
|
611
|
+
const newest = this.#archiveNumber(main.doc._pups?.archive_url)
|
|
612
|
+
if (newest === undefined) {
|
|
613
|
+
const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
|
|
614
|
+
if (indexed.changed || counterOf(main.doc) !== indexed.next)
|
|
615
|
+
await this.#writeMain({ ...main.doc, items: indexed.items, _pups: { ...main.doc._pups, next_index: indexed.next } }, main.etag, signal)
|
|
616
|
+
return
|
|
617
|
+
}
|
|
618
|
+
const archive = await this.#readArchive(this.#archivePath(newest), signal)
|
|
619
|
+
if (archive && archive != 'foreign' && (counterOf(archive.doc) === undefined || archive.doc.items.some(item => itemIndex(item) === undefined)))
|
|
620
|
+
await this.#indexArchives(main, signal)
|
|
621
|
+
})
|
|
510
622
|
}
|
|
511
623
|
|
|
512
624
|
/**
|
|
@@ -541,7 +653,8 @@ export class PupsFeed {
|
|
|
541
653
|
* a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
|
|
542
654
|
* function may run more than once.
|
|
543
655
|
*
|
|
544
|
-
* Apps should edit posts only when the owner asks them to, whichever app created them.
|
|
656
|
+
* Apps should edit posts only when the owner asks them to, whichever app created them. A post of a feed with
|
|
657
|
+
* archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
|
|
545
658
|
* @throws {PupsError} `not_found`
|
|
546
659
|
*/
|
|
547
660
|
async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: Signal = {}): Promise<PostResult> {
|
|
@@ -552,7 +665,13 @@ export class PupsFeed {
|
|
|
552
665
|
const fileUrl = this.#session.publicUrl(file.path)
|
|
553
666
|
const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes)
|
|
554
667
|
if (!changed) return this.#result(old, fileUrl)
|
|
555
|
-
const
|
|
668
|
+
const oldIndex = itemIndex(old)
|
|
669
|
+
let item: FeedItem = { ...changed, id, date_modified: now() }
|
|
670
|
+
// The index never changes (RFC-7 "Indexes").
|
|
671
|
+
if (oldIndex !== undefined) item = withIndex(item, oldIndex)
|
|
672
|
+
// A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
|
|
673
|
+
if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._pups?.archive_url) !== undefined)
|
|
674
|
+
item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal))
|
|
556
675
|
if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
|
|
557
676
|
const mainIndex = main.doc.items.findIndex(i => i.id == id)
|
|
558
677
|
if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
|
|
@@ -706,8 +825,10 @@ export class PupsFeed {
|
|
|
706
825
|
return fixed
|
|
707
826
|
}
|
|
708
827
|
|
|
709
|
-
|
|
710
|
-
|
|
828
|
+
/** Writes an archive with `items`, and with the counter `next_index` if given. */
|
|
829
|
+
async #writeArchive(archive: Loaded, items: FeedItem[], signal?: AbortSignal, nextIndex?: number) {
|
|
830
|
+
const doc = nextIndex === undefined ? { ...archive.doc, items } : { ...archive.doc, items, _pups: { ...archive.doc._pups, next_index: nextIndex } }
|
|
831
|
+
await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal })
|
|
711
832
|
}
|
|
712
833
|
|
|
713
834
|
/**
|
|
@@ -742,9 +863,9 @@ export class PupsFeed {
|
|
|
742
863
|
}
|
|
743
864
|
|
|
744
865
|
/** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
|
|
745
|
-
#newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined): FeedDocument {
|
|
866
|
+
#newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, nextIndex?: number): FeedDocument {
|
|
746
867
|
const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main
|
|
747
|
-
const { archive_url: _archive, ...marker } = _pups ?? {}
|
|
868
|
+
const { archive_url: _archive, next_index: _counter, ...marker } = _pups ?? {}
|
|
748
869
|
const podcast = fields._podcast
|
|
749
870
|
if (isObject(podcast) && 'liveItems' in podcast) {
|
|
750
871
|
const { liveItems: _live, ...rest } = podcast
|
|
@@ -758,12 +879,12 @@ export class PupsFeed {
|
|
|
758
879
|
user_comment: archiveComment(this.url),
|
|
759
880
|
...nextUrl ? { next_url: nextUrl } : {},
|
|
760
881
|
items,
|
|
761
|
-
_pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url },
|
|
882
|
+
_pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
|
|
762
883
|
}
|
|
763
884
|
}
|
|
764
885
|
|
|
765
|
-
async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal) {
|
|
766
|
-
await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl)), { contentType: FEED_CONTENT_TYPE, signal })
|
|
886
|
+
async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal, nextIndex?: number) {
|
|
887
|
+
await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl, nextIndex)), { contentType: FEED_CONTENT_TYPE, signal })
|
|
767
888
|
}
|
|
768
889
|
|
|
769
890
|
/**
|
|
@@ -782,17 +903,22 @@ export class PupsFeed {
|
|
|
782
903
|
|
|
783
904
|
/**
|
|
784
905
|
* Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
|
|
785
|
-
* archives"). The
|
|
786
|
-
*
|
|
906
|
+
* archives"). The items get indexes first, and the newest archive the counter. The oldest archive continues the
|
|
907
|
+
* feed's `next_url` chain.
|
|
908
|
+
* @returns the URL of the newest archive and the feed's items with their indexes, or undefined if the feed has no
|
|
909
|
+
* items.
|
|
787
910
|
*/
|
|
788
|
-
async #startArchives(main: Loaded, signal?: AbortSignal): Promise<string | undefined> {
|
|
789
|
-
const
|
|
911
|
+
async #startArchives(main: Loaded, signal?: AbortSignal): Promise<{ url: string; items: FeedItem[] } | undefined> {
|
|
912
|
+
const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
|
|
913
|
+
const oldestFirst = [...indexed.items].reverse()
|
|
914
|
+
const count = Math.ceil(oldestFirst.length / this.#archiveSize)
|
|
790
915
|
let url: string | undefined
|
|
791
|
-
for (let n = 0; n
|
|
916
|
+
for (let n = 0; n < count; n++) {
|
|
792
917
|
const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse()
|
|
793
918
|
const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url
|
|
919
|
+
const nextIndex = n == count - 1 ? indexed.next : undefined
|
|
794
920
|
try {
|
|
795
|
-
await this.#createArchive(n, main.doc, items, nextUrl, signal)
|
|
921
|
+
await this.#createArchive(n, main.doc, items, nextUrl, signal, nextIndex)
|
|
796
922
|
} catch (e) {
|
|
797
923
|
if (!isPupsError(e, 'precondition_failed')) throw e
|
|
798
924
|
// Left behind by an interrupted start: complete it, as long as it holds only these items.
|
|
@@ -800,53 +926,107 @@ export class PupsFeed {
|
|
|
800
926
|
const ids = new Set(items.map(item => item.id))
|
|
801
927
|
if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
|
|
802
928
|
throw new PupsError('conflict', `${this.#archivePath(n)} exists already, but ${this.path} has no archive_url. Remove the file, or set _pups.archive_url (RFC-7, Starting the archives).`)
|
|
803
|
-
await this.#writeArchive(existing, items, signal)
|
|
929
|
+
await this.#writeArchive(existing, items, signal, nextIndex)
|
|
804
930
|
}
|
|
805
931
|
url = this.#archiveUrl(n)
|
|
806
932
|
}
|
|
807
|
-
return url
|
|
933
|
+
return url ? { url, items: indexed.items } : undefined
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Indexes a feed with archives whose newest archive has no counter, or items without an index (RFC-7 "Indexing an
|
|
938
|
+
* existing feed"): gives every archived item without an index one, the oldest first, writes the changed archives
|
|
939
|
+
* from the oldest to the newest, the newest with the counter, and then the feed file's copies.
|
|
940
|
+
*/
|
|
941
|
+
async #indexArchives(main: Loaded, signal?: AbortSignal): Promise<void> {
|
|
942
|
+
const files: Loaded[] = []
|
|
943
|
+
for await (const file of this.#chain(main, signal)) {
|
|
944
|
+
// Pages behind the oldest archive of a handed-over feed are never written, and keep their items unindexed.
|
|
945
|
+
if (file == main || !isControlled(file.doc)) break
|
|
946
|
+
files.push(file)
|
|
947
|
+
}
|
|
948
|
+
if (!files.length) return
|
|
949
|
+
let next = nextFree(files.flatMap(file => file.doc.items), ...files.map(file => counterOf(file.doc)))
|
|
950
|
+
const indexes = new Map<string, number>()
|
|
951
|
+
for (const file of [...files].reverse()) {
|
|
952
|
+
const indexed = indexItems(file.doc.items, next)
|
|
953
|
+
next = indexed.next
|
|
954
|
+
for (const item of indexed.items) indexes.set(item.id, itemIndex(item)!)
|
|
955
|
+
const newest = file == files[0]
|
|
956
|
+
if (indexed.changed || (newest && counterOf(file.doc) !== next)) await this.#writeArchive(file, indexed.items, signal, newest ? next : undefined)
|
|
957
|
+
}
|
|
958
|
+
let changed = false
|
|
959
|
+
const items = main.doc.items.map(item => {
|
|
960
|
+
const index = indexes.get(item.id)
|
|
961
|
+
if (index === undefined || itemIndex(item) === index) return item
|
|
962
|
+
changed = true
|
|
963
|
+
return withIndex(item, index)
|
|
964
|
+
})
|
|
965
|
+
if (changed) await this.#writeMain({ ...main.doc, items }, main.etag, signal)
|
|
808
966
|
}
|
|
809
967
|
|
|
810
968
|
/**
|
|
811
969
|
* Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
|
|
812
970
|
* "Posting"). Writes only archives; the caller writes the feed file afterwards.
|
|
813
|
-
*
|
|
971
|
+
* The item gets its index from the archive's counter (RFC-7 "Indexes"); a newest archive without a counter is
|
|
972
|
+
* indexed first, and the post then starts again.
|
|
973
|
+
* @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
|
|
814
974
|
*/
|
|
815
|
-
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal): Promise<{ url: string; recent: FeedItem[] }> {
|
|
975
|
+
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal, template?: string): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
|
|
976
|
+
const place = (index: number) => this.#withPostUrl(withIndex(item, index), index, template)
|
|
816
977
|
const newest = this.#archiveNumber(doc._pups?.archive_url)
|
|
817
978
|
let previous: FeedItem[] = []
|
|
979
|
+
// The index for the item if it goes into a new archive.
|
|
980
|
+
let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined)
|
|
818
981
|
if (newest !== undefined) {
|
|
819
982
|
const existing = await this.#readArchive(this.#archivePath(newest), signal)
|
|
820
983
|
if (!existing) {
|
|
821
|
-
// The owner deleted it: create it again, linked to the next older archive.
|
|
822
|
-
|
|
823
|
-
|
|
984
|
+
// The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
|
|
985
|
+
const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined
|
|
986
|
+
if (before && before != 'foreign') next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc))
|
|
987
|
+
const stored = place(next)
|
|
988
|
+
await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1)
|
|
989
|
+
return { url: this.#archiveUrl(newest), recent: [stored], item: stored }
|
|
824
990
|
}
|
|
825
991
|
if (existing != 'foreign') {
|
|
826
|
-
|
|
992
|
+
if (counterOf(existing.doc) === undefined) {
|
|
993
|
+
await this.#indexArchives(main, signal)
|
|
994
|
+
throw conflict(`${this.path} was indexed, so it`)
|
|
995
|
+
}
|
|
996
|
+
// Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
|
|
997
|
+
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)))
|
|
998
|
+
const copy = indexed.items.find(i => i.id == item.id)
|
|
999
|
+
const stored = place(copy ? itemIndex(copy)! : indexed.next)
|
|
1000
|
+
const merged = mergeItems(indexed.items, [stored])
|
|
827
1001
|
if (merged.length <= this.#archiveSize) {
|
|
828
|
-
await this.#writeArchive(existing, merged, signal)
|
|
829
|
-
return { url: this.#archiveUrl(newest), recent: merged }
|
|
1002
|
+
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
|
|
1003
|
+
return { url: this.#archiveUrl(newest), recent: merged, item: stored }
|
|
830
1004
|
}
|
|
831
|
-
|
|
1005
|
+
if (indexed.changed) await this.#writeArchive(existing, indexed.items, signal, indexed.next)
|
|
1006
|
+
previous = indexed.items
|
|
1007
|
+
next = indexed.next
|
|
832
1008
|
}
|
|
833
1009
|
}
|
|
834
1010
|
// The archive before the new one: the newest, or for a feed without archives the end of its old chain.
|
|
835
1011
|
const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest)
|
|
836
1012
|
for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
|
|
1013
|
+
const stored = place(next)
|
|
837
1014
|
try {
|
|
838
|
-
await this.#createArchive(n, doc, [
|
|
839
|
-
return { url: this.#archiveUrl(n), recent: [
|
|
1015
|
+
await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1)
|
|
1016
|
+
return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored }
|
|
840
1017
|
} catch (e) {
|
|
841
1018
|
if (!isPupsError(e, 'precondition_failed')) throw e
|
|
842
1019
|
}
|
|
843
1020
|
// The archive exists: left behind by an interrupted client, or created by another client just now.
|
|
844
1021
|
const existing = await this.#readArchive(this.#archivePath(n), signal)
|
|
845
1022
|
if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
|
|
846
|
-
const
|
|
1023
|
+
const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next))
|
|
1024
|
+
const copy = indexed.items.find(i => i.id == item.id)
|
|
1025
|
+
const added = place(copy ? itemIndex(copy)! : indexed.next)
|
|
1026
|
+
const merged = mergeItems(indexed.items, [added])
|
|
847
1027
|
if (merged.length <= this.#archiveSize) {
|
|
848
|
-
await this.#writeArchive(existing, merged, signal)
|
|
849
|
-
return { url: this.#archiveUrl(n), recent: [...merged, ...previous] }
|
|
1028
|
+
await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
|
|
1029
|
+
return { url: this.#archiveUrl(n), recent: [...merged, ...previous], item: added }
|
|
850
1030
|
}
|
|
851
1031
|
}
|
|
852
1032
|
const current = await this.#session.get(this.path, { signal })
|
|
@@ -857,6 +1037,22 @@ export class PupsFeed {
|
|
|
857
1037
|
|
|
858
1038
|
// Items and media
|
|
859
1039
|
|
|
1040
|
+
/** The site's post URL template from `host-meta.json`, read once; undefined if there is none or it can't be read. */
|
|
1041
|
+
#postUrlTemplate(signal?: AbortSignal): Promise<string | undefined> {
|
|
1042
|
+
if (!this.#postUrls) return Promise.resolve(undefined)
|
|
1043
|
+
this.#template ??= this.#session.hostMeta.get({ signal })
|
|
1044
|
+
.then(doc => doc.properties?.[POST_URL_TEMPLATE])
|
|
1045
|
+
.then(template => validTemplate(template) ? template : undefined, () => undefined)
|
|
1046
|
+
return this.#template
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** The item with the `url` from the post URL template (RFC-7 "Post URLs"), unless it has one. */
|
|
1050
|
+
#withPostUrl(item: FeedItem, index: number, template?: string): FeedItem {
|
|
1051
|
+
if (!template || item.url) return item
|
|
1052
|
+
const vars: Record<string, string> = { feed: this.path.slice(1, -'.json'.length), index: String(index), id: encodeURIComponent(item.id) }
|
|
1053
|
+
return { ...item, url: template.replace(/\{(feed|index|id)\}/g, (_, name: string) => vars[name]!) }
|
|
1054
|
+
}
|
|
1055
|
+
|
|
860
1056
|
#newItem(input: PostInput): FeedItem {
|
|
861
1057
|
const { id, markdown, date_published, ...fields } = input
|
|
862
1058
|
if (id !== undefined && (typeof id != 'string' || !id))
|
|
@@ -869,6 +1065,12 @@ export class PupsFeed {
|
|
|
869
1065
|
if (markdown !== undefined) this.#setMarkdown(item, markdown)
|
|
870
1066
|
if (item.content_html === undefined && item.content_text === undefined)
|
|
871
1067
|
throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).')
|
|
1068
|
+
// The index is given out when the item is added (RFC-7 "Indexes").
|
|
1069
|
+
if (isObject(item._pups)) {
|
|
1070
|
+
const { index: _index, ...marker } = item._pups
|
|
1071
|
+
if (Object.keys(marker).length) item._pups = marker
|
|
1072
|
+
else delete item._pups
|
|
1073
|
+
}
|
|
872
1074
|
return item
|
|
873
1075
|
}
|
|
874
1076
|
|
|
@@ -900,7 +1102,8 @@ export class PupsFeed {
|
|
|
900
1102
|
}
|
|
901
1103
|
|
|
902
1104
|
#result(item: FeedItem, fileUrl: string): PostResult {
|
|
903
|
-
|
|
1105
|
+
const index = itemIndex(item)
|
|
1106
|
+
return { id: item.id, ...index === undefined ? {} : { index }, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` }
|
|
904
1107
|
}
|
|
905
1108
|
|
|
906
1109
|
/**
|
|
@@ -935,7 +1138,8 @@ export class PupsFeed {
|
|
|
935
1138
|
const path = `${this.directory}${prefix}${randomString(9)}.${extension}`
|
|
936
1139
|
const result = await this.#session.create(path, body, { signal })
|
|
937
1140
|
const size = typeof body == 'string' ? byteLength(body) : body instanceof Blob ? body.size : (body as ArrayBuffer | ArrayBufferView).byteLength
|
|
938
|
-
|
|
1141
|
+
// Feed directories are public, so the result always has a URL.
|
|
1142
|
+
return { path, url: result.url!, type, size }
|
|
939
1143
|
}
|
|
940
1144
|
|
|
941
1145
|
async #setImage(field: 'icon' | 'favicon', media: MediaInput | null, signal?: AbortSignal): Promise<FeedDocument> {
|
package/src/host-meta.ts
CHANGED
|
@@ -10,6 +10,8 @@ export interface HostMetaLink {
|
|
|
10
10
|
rel: string
|
|
11
11
|
href?: string
|
|
12
12
|
type?: string
|
|
13
|
+
/** A language tag or `default` → a title (RFC 7033). */
|
|
14
|
+
titles?: Record<string, string>
|
|
13
15
|
properties?: Record<string, string | null>
|
|
14
16
|
[field: string]: unknown
|
|
15
17
|
}
|
|
@@ -92,16 +94,48 @@ export class HostMetaEditor {
|
|
|
92
94
|
return [...new Set(properties)]
|
|
93
95
|
}
|
|
94
96
|
|
|
97
|
+
/** The link properties allowed for links to the file `href` (a path or a public URL): those declared for its well-known path. */
|
|
98
|
+
allowedLinkProperties(href: string): string[] {
|
|
99
|
+
try {
|
|
100
|
+
return wellKnownEntryFor(this.#target(href).path, this.#session.server.wellKnownPaths)?.linkProperties ?? []
|
|
101
|
+
} catch {
|
|
102
|
+
return []
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
95
106
|
/**
|
|
96
|
-
* Adds a link to one of the app's files
|
|
97
|
-
* a
|
|
98
|
-
*
|
|
107
|
+
* Adds a link to one of the app's files, or changes it if the app added it before: its `type`, `titles` and
|
|
108
|
+
* `properties` are then replaced (omitted ones removed). `href` may be a path (relative paths are in the app's own
|
|
109
|
+
* directory) or a public URL; it is sent as the public URL. `titles` maps language tags or `default` to titles;
|
|
110
|
+
* `properties` may only hold the link properties declared for the file's well-known path.
|
|
111
|
+
* @throws {PupsError} `insufficient_scope` if the file, rel or a property isn't allowed, `conflict` if a single-valued
|
|
112
|
+
* rel is taken or the link belongs to the owner or another app.
|
|
99
113
|
*/
|
|
100
|
-
async addLink(link: { rel: string; href: string; type?: string
|
|
114
|
+
async addLink(link: { rel: string; href: string; type?: string; titles?: Record<string, string>; properties?: Record<string, string> },
|
|
115
|
+
options: { signal?: AbortSignal } = {}): Promise<void> {
|
|
101
116
|
const { url } = this.#target(link.href)
|
|
102
117
|
if (!this.allowsRel(link.rel, link.href))
|
|
103
118
|
throw new PupsError('insufficient_scope', `The granted scopes don't allow the rel "${link.rel}" for ${url} (RFC-6, Links).`)
|
|
104
|
-
|
|
119
|
+
const allowed = this.allowedLinkProperties(link.href)
|
|
120
|
+
const bad = Object.keys(link.properties ?? {}).find(p => !allowed.includes(p))
|
|
121
|
+
if (bad)
|
|
122
|
+
throw new PupsError('insufficient_scope', `The link property "${bad}" isn't allowed for ${url}. Allowed: ${allowed.join(', ') || 'none'} (RFC-6, Links).`)
|
|
123
|
+
await this.#post({
|
|
124
|
+
action: 'add', rel: link.rel, href: url, ...link.type ? { type: link.type } : {},
|
|
125
|
+
...link.titles ? { titles: link.titles } : {}, ...link.properties ? { properties: link.properties } : {},
|
|
126
|
+
}, `Adding a ${link.rel} link`, options.signal)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Puts the links of `rel` into the order of `hrefs` (public URLs, or paths of files in the scopes). It must list
|
|
131
|
+
* every link of that rel in `host-meta.json` exactly once, the owner's and other apps' included; read them with
|
|
132
|
+
* {@link get} first.
|
|
133
|
+
* @throws {PupsError} `conflict` if `hrefs` doesn't match the current links, `insufficient_scope` if no granted
|
|
134
|
+
* scope allows the rel.
|
|
135
|
+
*/
|
|
136
|
+
async orderLinks(rel: string, hrefs: string[], options: { signal?: AbortSignal } = {}): Promise<void> {
|
|
137
|
+
const urls = hrefs.map(h => /^[a-z][a-z0-9+.-]*:/i.test(h) ? h : this.#target(h).url)
|
|
138
|
+
await this.#post({ action: 'order', rel, hrefs: urls }, `Ordering the ${rel} links`, options.signal)
|
|
105
139
|
}
|
|
106
140
|
|
|
107
141
|
/** Removes a link the app added. Links of the owner and of other apps are never touched by the server. */
|
|
@@ -124,7 +158,7 @@ export class HostMetaEditor {
|
|
|
124
158
|
}
|
|
125
159
|
|
|
126
160
|
/**
|
|
127
|
-
* The path and public URL of a link target, which must be a file inside the granted scopes.
|
|
161
|
+
* The path and public URL of a link target, which must be a public file inside the granted scopes.
|
|
128
162
|
* @throws {PupsError} `insufficient_scope`
|
|
129
163
|
*/
|
|
130
164
|
#target(href: string): { path: string; url: string } {
|
|
@@ -132,10 +166,12 @@ export class HostMetaEditor {
|
|
|
132
166
|
const path = /^[a-z][a-z0-9+.-]*:/i.test(href) ? pathFromPublicUrl(session.server, href) : session.resolve(href)
|
|
133
167
|
if (!path || !session.canWrite(path))
|
|
134
168
|
throw new PupsError('insufficient_scope', `"${href}" is not a file inside the scopes granted to this app. Links may only point to the app's own files (RFC-6, Links).`)
|
|
169
|
+
if (session.isPrivate(path))
|
|
170
|
+
throw new PupsError('insufficient_scope', `"${href}" is private: it has no public URL and can't be linked (RFC-6, Private areas).`)
|
|
135
171
|
return { path, url: session.publicUrl(path) }
|
|
136
172
|
}
|
|
137
173
|
|
|
138
|
-
async #post(body: Record<string,
|
|
174
|
+
async #post(body: Record<string, unknown>, what: string, signal?: AbortSignal) {
|
|
139
175
|
const endpoint = this.#session.server.hostMetaEndpoint
|
|
140
176
|
if (!endpoint) throw new PupsError('unsupported', `${new URL(this.#session.server.domain).host}'s server can't edit host-meta.json.`)
|
|
141
177
|
const response = await this.#session._authorized(endpoint, {
|
package/src/index.ts
CHANGED
|
@@ -16,7 +16,7 @@ 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 } from './feed.js'
|
|
19
|
+
export { FEED_REL, POST_URL_TEMPLATE, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
|
|
20
20
|
export type {
|
|
21
21
|
FeedAttachment,
|
|
22
22
|
FeedAuthor,
|
|
@@ -28,6 +28,7 @@ export type {
|
|
|
28
28
|
FeedSettingsChanges,
|
|
29
29
|
FeedSetup,
|
|
30
30
|
FeedState,
|
|
31
|
+
ItemMarker,
|
|
31
32
|
MediaInput,
|
|
32
33
|
MediaResult,
|
|
33
34
|
PostChanges,
|
package/src/paths.ts
CHANGED
|
@@ -64,21 +64,39 @@ export function wellKnownEntryFor(path: string, wellKnownPaths: readonly WellKno
|
|
|
64
64
|
return best
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* Whether an absolute path is in a private area (RFC-6 "Private areas"): `/pups/private/…`, or the `private/`
|
|
69
|
+
* folder of an app's own directory, `/appdata/<client-host>/private/…`. Private files are read only with a token
|
|
70
|
+
* whose scope covers them, and have no public URL. Case-insensitive, like the servers, whose disk may be.
|
|
71
|
+
*/
|
|
72
|
+
export const isPrivate = (path: string) => /^\/(pups\/private\/|appdata\/[^/]+\/private\/[^/])/i.test(path)
|
|
73
|
+
|
|
67
74
|
/** The URL where `path` is written (RFC-6 "Upload API"). */
|
|
68
75
|
export const storageUrl = (server: PupsServer, path: string) => server.storageBase + encodePath(path).slice(1)
|
|
69
76
|
|
|
70
77
|
/**
|
|
71
78
|
* The URL where readers find `path` (RFC-6 "Public URLs"): `public_base` + path, or, for a file under a
|
|
72
79
|
* well-known entry with a `url`, that `url` plus the rest of the path.
|
|
80
|
+
* @throws {PupsError} `invalid_path` for a private file, which has no public URL.
|
|
73
81
|
*/
|
|
74
82
|
export function publicUrl(server: PupsServer, path: string): string {
|
|
83
|
+
if (isPrivate(path))
|
|
84
|
+
throw new PupsError('invalid_path', `${path} is private and has no public URL. Read it with get() (RFC-6, Private areas).`)
|
|
75
85
|
const entry = wellKnownEntryFor(path, server.wellKnownPaths)
|
|
76
86
|
if (entry?.url) return entry.url + encodePath(path.slice(entry.path.length))
|
|
77
87
|
return server.publicBase + encodePath(path).slice(1)
|
|
78
88
|
}
|
|
79
89
|
|
|
80
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* The path of a public URL, the reverse of {@link publicUrl}, or undefined if the URL is not a public file of this
|
|
92
|
+
* server. Private files have no public URL, so a URL that maps to one is not a public file either.
|
|
93
|
+
*/
|
|
81
94
|
export function pathFromPublicUrl(server: PupsServer, url: string): string | undefined {
|
|
95
|
+
const path = mapPublicUrl(server, url)
|
|
96
|
+
return path && !isPrivate(path) ? path : undefined
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function mapPublicUrl(server: PupsServer, url: string): string | undefined {
|
|
82
100
|
try {
|
|
83
101
|
const entries = server.wellKnownPaths.filter(w => w.url).sort((a, b) => b.url!.length - a.url!.length)
|
|
84
102
|
for (const entry of entries)
|