pups-client 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/feed.ts CHANGED
@@ -12,7 +12,7 @@ export const FEED_REL = 'https://bigwide.net/ns/feed'
12
12
 
13
13
  /**
14
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").
15
+ * `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs"). The server fills it into new posts.
16
16
  */
17
17
  export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template'
18
18
 
@@ -26,13 +26,6 @@ const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for
26
26
  const RFC4_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-4-Feed-Submissions.md'
27
27
  const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1'
28
28
  const FEED_CONTENT_TYPE = 'application/feed+json'
29
- const maxArchiveNumber = 999_999
30
- /** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
31
- const minFeedItems = 10
32
-
33
- const mainComment = `This feed is maintained by apps through a Personal Upload Server (PUPS), following ${PUPS_FEED_SPEC}. It contains the newest items. If it has _archive.archive_url, all items are in the archives, starting with the one there.`
34
- const archiveComment = (feedUrl: string) =>
35
- `This is an archive of ${feedUrl}, maintained by apps through a Personal Upload Server (PUPS), following ${PUPS_FEED_SPEC}. New items appear in the feed at _archive.updates_url, older ones are in the archive at next_url.`
36
29
 
37
30
  /** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
38
31
  const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
@@ -88,9 +81,6 @@ export interface ItemArchive {
88
81
  [field: string]: unknown
89
82
  }
90
83
 
91
- /** @deprecated The index moved from `_pups` to `_archive` (RFC-13): use ItemArchive. */
92
- export type ItemMarker = ItemArchive
93
-
94
84
  /** The `_pups` object of a feed file or archive: the marker of RFC-7. */
95
85
  export interface PupsMarker {
96
86
  about?: string
@@ -98,7 +88,7 @@ export interface PupsMarker {
98
88
  [field: string]: unknown
99
89
  }
100
90
 
101
- /** The `_archive` object of a feed file or archive (RFC-13). */
91
+ /** The `_archive` object of a feed file or archive (RFC-13). The server writes it. */
102
92
  export interface ArchiveFields {
103
93
  about?: string
104
94
  /** In the feed file: the public URL of the newest archive. */
@@ -111,10 +101,7 @@ export interface ArchiveFields {
111
101
  updates_url?: string
112
102
  /** In an archive: its number, from 0 for the oldest. */
113
103
  number?: number
114
- /**
115
- * The index the next new item gets (RFC-13 "Indexes"). Valid in the newest archive, or in the feed file of a feed
116
- * without archives.
117
- */
104
+ /** In the newest archive: the index the next new item gets (RFC-13 "Indexes"). */
118
105
  next_index?: number
119
106
  [field: string]: unknown
120
107
  }
@@ -222,13 +209,13 @@ export type PostChanges = { [K in Exclude<keyof PostInput, 'id'>]?: PostInput[K]
222
209
 
223
210
  export interface PostResult {
224
211
  id: string
225
- /** The item's index (RFC-7 "Indexes"); undefined for an item that has none yet. */
212
+ /** The item's index (RFC-13 "Indexes"). */
226
213
  index?: number
227
214
  /** The item as stored. */
228
215
  item: FeedItem
229
216
  /**
230
- * The URL of the item's archive plus `#<id>`. Items never leave their archive, so it never changes; use it e.g.
231
- * as the `source` of an RFC-4 webmention. In a feed without archives, the feed file's URL plus `#<id>`.
217
+ * The item's address: the URL of its archive plus `#<id>` (RFC-13 "Items"). Items never leave their archive, so it
218
+ * never changes; use it e.g. as the `source` of an RFC-4 webmention. The post's page, if it has one, is `item.url`.
232
219
  */
233
220
  url: string
234
221
  /**
@@ -250,7 +237,7 @@ export interface MediaResult {
250
237
  export type FeedState =
251
238
  /** There is no feed file yet. `create()` sets it up. */
252
239
  | { status: 'missing' }
253
- /** A feed maintained by PUPS clients, ready to write. */
240
+ /** A feed kept by the PUPS server, ready to write. */
254
241
  | { status: 'pups'; feed: FeedDocument; etag: string }
255
242
  /** A JSON Feed without `_pups.pupsControlled`: maintained by other means, and never written (RFC-7). */
256
243
  | { status: 'foreign'; feed: FeedDocument }
@@ -258,28 +245,8 @@ export type FeedState =
258
245
  | { status: 'invalid' }
259
246
 
260
247
  export interface FeedOptions {
261
- /** How many of the newest items the feed file holds. Default 30 (RFC-7 "Feed size"). */
262
- maxItems?: number
263
- /** How many items an archive holds. Default 20 (RFC-7 "Archives"); other clients expect 20. */
264
- archiveSize?: number
265
- /**
266
- * Whether to start archives for a feed that has none, on its next post (RFC-7 "Starting the archives").
267
- * Default true. With false, posts to such a feed only go into the feed file, and items beyond `maxItems` are
268
- * dropped. Feeds that have archives always keep them.
269
- */
270
- startArchives?: boolean
271
- /**
272
- * Optional: keep fewer items in the feed file when it would be larger than this many bytes, but at least 10
273
- * (RFC-7 "Size in bytes").
274
- */
275
- maxBytes?: number
276
- /** How often an operation is repeated when another client changed the feed in between. Default 8. */
248
+ /** How often a change of the feed's settings is repeated when someone changed the feed in between. Default 8. */
277
249
  maxAttempts?: number
278
- /**
279
- * Whether posts of a feed with archives get a `url` from the site's post URL template, if `host-meta.json`
280
- * declares one and the post has no `url` (RFC-7 "Post URLs"). Default true.
281
- */
282
- postUrls?: boolean
283
250
  /**
284
251
  * Whether to send RFC-11 mentions after `addPost()`, `editPost()` and `deletePost()`: to the domains a post names
285
252
  * (`@tim.example.com`) and to the author of the item it answers. `true` uses `session.mentions`. Default false.
@@ -312,10 +279,10 @@ interface Loaded {
312
279
  etag: string
313
280
  }
314
281
 
315
- interface Found {
316
- main: Loaded
317
- file: Loaded
318
- index: number
282
+ /** The server's answer to a POST of an item (RFC-7 "Posting items"). */
283
+ interface Posted {
284
+ item: FeedItem
285
+ address: string
319
286
  }
320
287
 
321
288
  /** The scopes an app needs to write a feed: the feed file and the feed directory (RFC-7 "Server requirements"). */
@@ -333,7 +300,6 @@ function feedPaths(name?: string): { path: `/${string}`; directory: `/${string}`
333
300
  return { path: `/feed/${name}.json`, directory: `/feed/${name}/` }
334
301
  }
335
302
 
336
-
337
303
  const isFeedDocument = (value: unknown): value is FeedDocument =>
338
304
  isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
339
305
  && Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string')
@@ -341,9 +307,7 @@ const isFeedDocument = (value: unknown): value is FeedDocument =>
341
307
  const isControlled = (doc: FeedDocument) => doc._pups?.pupsControlled === true
342
308
 
343
309
  const notControlled = (path: string) =>
344
- new PupsError('not_pups_controlled', `${path} is not maintained by PUPS clients: it has no "_pups": { "pupsControlled": true }. It is never written; the owner can hand it over by adding that marker (RFC-7, The _pups object).`)
345
-
346
- const conflict = (what: string) => new PupsError('precondition_failed', `${what} changed in the meantime.`)
310
+ new PupsError('not_pups_controlled', `${path} is not kept by PUPS: it has no "_pups": { "pupsControlled": true }. It is never written; the owner can hand it over by adding that marker (RFC-7, The _pups object).`)
347
311
 
348
312
  const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
349
313
 
@@ -353,88 +317,12 @@ const serialize = (doc: FeedDocument) => JSON.stringify(doc, null, 2)
353
317
 
354
318
  const byteLength = (text: string) => new TextEncoder().encode(text).length
355
319
 
356
- const replaceAt = <T>(array: T[], index: number, value: T) => array.map((v, i) => i == index ? value : v)
357
-
358
- /** Adds `incoming` items at the top of `existing`; an item whose id is already there replaces the old copy instead. */
359
- function mergeItems(existing: FeedItem[], incoming: FeedItem[]): FeedItem[] {
360
- const byId = new Map(incoming.map(item => [item.id, item]))
361
- const present = new Set(existing.map(item => item.id))
362
- return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)]
363
- }
364
-
365
- /** The index of an item (RFC-13 "Indexes"), also from `_pups` of earlier drafts, or undefined if it has none. */
320
+ /** The index of an item (RFC-13 "Indexes"), or undefined if it has none. */
366
321
  export function itemIndex(item: FeedItem): number | undefined {
367
- const index = isObject(item._archive) && item._archive.index !== undefined ? item._archive.index : isObject(item._pups) ? item._pups.index : undefined
322
+ const index = isObject(item._archive) ? item._archive.index : undefined
368
323
  return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined
369
324
  }
370
325
 
371
- const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _archive: { ...isObject(item._archive) ? item._archive : {}, index } })
372
-
373
- /** The fields of RFC-13 that earlier drafts of RFC-7 kept in `_pups`. */
374
- const legacyArchiveFields = ['archive_url', 'updates_url', 'next_index'] as const
375
-
376
- /**
377
- * Moves the fields that earlier drafts kept in `_pups` into `_archive` (RFC-13 "Earlier drafts"), in the file and its
378
- * items, where `_archive` doesn't have them already. Changes `doc`.
379
- */
380
- function upgradeArchiveFields(doc: FeedDocument): FeedDocument {
381
- const move = (from: Record<string, unknown>, to: Record<string, unknown>, keys: readonly string[]) => {
382
- for (const key of keys) if (key in from) {
383
- if (to[key] === undefined) to[key] = from[key]
384
- delete from[key]
385
- }
386
- }
387
- if (isObject(doc._pups) && legacyArchiveFields.some(key => key in doc._pups!)) {
388
- const archive: ArchiveFields = { about: ARCHIVE_SPEC, ...isObject(doc._archive) ? doc._archive : {} }
389
- move(doc._pups, archive, legacyArchiveFields)
390
- doc._archive = archive
391
- }
392
- for (const item of doc.items)
393
- if (isObject(item._pups) && 'index' in item._pups) {
394
- const archive: ItemArchive = isObject(item._archive) ? item._archive : {}
395
- move(item._pups, archive, ['index'])
396
- item._archive = archive
397
- if (!Object.keys(item._pups).length) delete item._pups
398
- }
399
- return doc
400
- }
401
-
402
- /** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
403
- function validTemplate(template: unknown): template is string {
404
- if (typeof template != 'string' || !/\{(index|id)\}/.test(template)) return false
405
- try {
406
- return new URL(template.replace(/\{(feed|index|id)\}/g, 'x')).protocol == 'https:'
407
- } catch {
408
- return false
409
- }
410
- }
411
-
412
- /** The counter `_archive.next_index` of a file, if it has a valid one. */
413
- function counterOf(doc: FeedDocument): number | undefined {
414
- const next = doc._archive?.next_index
415
- return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined
416
- }
417
-
418
- /** The next free index: above every index of `items`, and at least each of `counters`. */
419
- const nextFree = (items: FeedItem[], ...counters: (number | undefined)[]) =>
420
- Math.max(0, ...counters.filter((c): c is number => c !== undefined), ...items.map(item => (itemIndex(item) ?? -1) + 1))
421
-
422
- /**
423
- * Gives the items without an index (newest first, as in a file) the next indexes from `next`, the oldest first
424
- * (RFC-7 "Items without an index").
425
- * @returns the items, and the counter after them.
426
- */
427
- function indexItems(items: FeedItem[], next: number): { items: FeedItem[]; next: number; changed: boolean } {
428
- const result = [...items]
429
- let changed = false
430
- for (let i = result.length - 1; i >= 0; i--)
431
- if (itemIndex(result[i]!) === undefined) {
432
- result[i] = withIndex(result[i]!, next++)
433
- changed = true
434
- }
435
- return { items: result, next, changed }
436
- }
437
-
438
326
  /** Every string inside `value`, deeply. */
439
327
  function* strings(value: unknown): Generator<string> {
440
328
  if (typeof value == 'string') yield value
@@ -449,15 +337,26 @@ function extensionForType(type: string): string | undefined {
449
337
  return entries.find(([, t]) => t.served == essence)?.[0] ?? entries.find(([, t]) => t.accepted.includes(essence))?.[0]
450
338
  }
451
339
 
340
+ /** The answer to a POST of an item, checked. */
341
+ function posted(body: unknown, path: string): Posted {
342
+ if (!isObject(body) || !isObject(body.item) || typeof body.item.id != 'string' || typeof body.address != 'string')
343
+ throw new PupsError('server_error', `The server's answer to the POST to ${path} has no item and address (RFC-7, Posting items).`)
344
+ return { item: body.item as FeedItem, address: body.address }
345
+ }
346
+
347
+ /** The file part of an item's address. */
348
+ const fileOf = (address: string) => address.split('#')[0]!
349
+
452
350
  /**
453
- * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json`, or a named feed
454
- * `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
351
+ * A feed on the owner's domain, kept by the PUPS server according to RFC-7: the main feed `/feed.json`, or a named
352
+ * feed `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
455
353
  * The main feed keeps its media in `/feed/images/` and `/feed/media/`, since the rest of `/feed/` belongs to the
456
354
  * named feeds.
457
355
  *
458
356
  * Get one from `session.feed()` or `session.feed('photos')`. The session needs the feed's scopes, see
459
- * {@link feedScopes}. All writes are safe against concurrent changes by other apps and the owner: they are
460
- * read-modify-write cycles with ETags, repeated when another client wrote in between.
357
+ * {@link feedScopes}. Posts are sent to the server one at a time, which gives them their index and puts them into
358
+ * the archives (RFC-13); changes of the feed's settings are read-modify-write cycles with ETags, repeated when
359
+ * another app wrote in between.
461
360
  */
462
361
  export class PupsFeed {
463
362
  /** The name of a named feed; undefined for the main feed. */
@@ -467,14 +366,8 @@ export class PupsFeed {
467
366
  /** The feed directory, e.g. `/feed/` or `/feed/photos/`. */
468
367
  readonly directory: string
469
368
  readonly #session: PupsSession
470
- readonly #maxItems: number
471
- readonly #archiveSize: number
472
- readonly #archivesWanted: boolean
473
- readonly #maxBytes?: number
474
369
  readonly #maxAttempts: number
475
- readonly #postUrls: boolean
476
370
  readonly #mentions?: Mentions
477
- #template?: Promise<string | undefined>
478
371
 
479
372
  /** @internal Use `session.feed()`. */
480
373
  constructor(session: PupsSession, name?: string, options: FeedOptions = {}) {
@@ -483,15 +376,8 @@ export class PupsFeed {
483
376
  this.path = path
484
377
  this.directory = directory
485
378
  this.#session = session
486
- this.#maxItems = options.maxItems ?? 30
487
- this.#archiveSize = options.archiveSize ?? 20
488
- this.#archivesWanted = options.startArchives ?? true
489
- this.#maxBytes = options.maxBytes
490
379
  this.#maxAttempts = options.maxAttempts ?? 8
491
- this.#postUrls = options.postUrls ?? true
492
380
  this.#mentions = options.mentions === true ? session.mentions : options.mentions || undefined
493
- if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
494
- throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.')
495
381
  }
496
382
 
497
383
  /** The public URL of the feed file, its `feed_url`. */
@@ -506,10 +392,10 @@ export class PupsFeed {
506
392
 
507
393
  /** Whether the session may write the feed file and the feed directory. */
508
394
  get writable(): boolean {
509
- return this.#session.canWrite(this.path) && this.#session.canWrite(this.#archivePath(0))
395
+ return this.#session.canWrite(this.path) && this.#session.canWrite(`${this.directory}images/x`)
510
396
  }
511
397
 
512
- /** Reads the feed file and tells whether it exists, and whether PUPS clients may write it. */
398
+ /** Reads the feed file and tells whether it exists, and whether the server keeps it. */
513
399
  async load(options: Signal = {}): Promise<FeedState> {
514
400
  try {
515
401
  const loaded = await this.#read(this.path, options.signal)
@@ -522,17 +408,19 @@ export class PupsFeed {
522
408
  }
523
409
 
524
410
  /**
525
- * Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the fixed fields
526
- * and the `_pups` marker, and registers the feed in `host-meta.json` (unless `register` is false).
411
+ * Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the `_pups` marker,
412
+ * and registers the feed in `host-meta.json` (unless `register` is false). The server sets the fixed fields.
527
413
  * @returns `registered`: false if the feed couldn't be registered; call `register()` again later, or tell the owner
528
414
  * to add the link to `host-meta.json` by hand.
529
- * @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`.
415
+ * @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`; `unsupported` if
416
+ * the server doesn't keep feeds.
530
417
  */
531
418
  async create(setup: FeedSetup, options: Signal & { register?: boolean } = {}): Promise<{ url: string; registered: boolean }> {
532
419
  const { icon, favicon, title, ...settings } = setup
533
420
  if (typeof title != 'string' || !title.trim()) throw new PupsError('invalid_request', 'A feed needs a title.')
534
421
  this.#checkSettings(settings)
535
422
  this.#checkWritable()
423
+ this.#checkKept()
536
424
  const uploaded: MediaResult[] = []
537
425
  try {
538
426
  const iconFile = icon && await this.#upload(icon, 'images/icons/icon-', options.signal)
@@ -543,10 +431,7 @@ export class PupsFeed {
543
431
  const doc: FeedDocument = {
544
432
  version: JSON_FEED_VERSION,
545
433
  title,
546
- home_page_url: this.#session.me,
547
- feed_url: this.url,
548
434
  ...description === undefined ? {} : { description },
549
- user_comment: mainComment,
550
435
  ...iconFile ? { icon: iconFile.url } : {},
551
436
  ...faviconFile ? { favicon: faviconFile.url } : {},
552
437
  ...rest,
@@ -592,14 +477,11 @@ export class PupsFeed {
592
477
  this.#checkSettings(changes)
593
478
  if (changes.title === null || (changes.title !== undefined && !changes.title.trim()))
594
479
  throw new PupsError('invalid_request', 'A feed needs a title.')
595
- return this.#transaction(async () => {
596
- const main = await this.#readControlled(this.path, options.signal)
597
- const doc = { ...main.doc }
480
+ return this.#change(doc => {
598
481
  for (const [key, value] of Object.entries(changes))
599
482
  if (value === null) delete doc[key]
600
483
  else if (value !== undefined) doc[key] = value
601
- return this.#writeMain(doc, main.etag, options.signal)
602
- })
484
+ }, options.signal)
603
485
  }
604
486
 
605
487
  /**
@@ -654,11 +536,10 @@ export class PupsFeed {
654
536
  }
655
537
 
656
538
  #setSubmissions(submissions: Record<string, unknown> | undefined, signal?: AbortSignal): Promise<FeedDocument> {
657
- return this.#transaction(async () => {
658
- const main = await this.#readControlled(this.path, signal)
659
- const { _submissions: _old, ...doc } = main.doc
660
- return this.#writeMain(submissions ? { ...doc, _submissions: submissions } : doc, main.etag, signal)
661
- })
539
+ return this.#change(doc => {
540
+ if (submissions) doc._submissions = submissions
541
+ else delete doc._submissions
542
+ }, signal)
662
543
  }
663
544
 
664
545
  /**
@@ -677,95 +558,33 @@ export class PupsFeed {
677
558
  }
678
559
 
679
560
  /**
680
- * Adds a post (RFC-7 "Posting with archives"): first to the newest archive, or to a new archive once the newest
681
- * holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
682
- * archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
683
- * media with `uploadMedia()` before posting.
684
- * In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
685
- * has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
561
+ * Adds a post (RFC-7 "Posting items"): sends it to the server, which gives it its index, puts it into the newest
562
+ * archive and at the top of the feed file, and, if the site declares a post URL template, gives it the `url` of
563
+ * its page. Upload media with `uploadMedia()` before posting.
686
564
  * With the option `mentions`, the domains the post names and the author of the item it answers are notified
687
565
  * (RFC-11) once the post is visible; see `PostResult.mentions`.
688
- * @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
689
- * archives, the feed file's URL plus `#<id>`, valid while the post is among the newest. The post's page, if it
690
- * has one, is `item.url`.
566
+ * @returns the post as stored, with `url`: its address, which never changes. The post's page, if it has one, is
567
+ * `item.url`.
568
+ * @throws {PupsError} `not_found` if the feed doesn't exist; `not_pups_controlled`; `unsupported` if the server
569
+ * doesn't keep feeds.
691
570
  */
692
571
  async addPost(input: PostInput, options: WithMentions = {}): Promise<PostResult> {
693
- const item = this.#newItem(input)
694
- const signal = options.signal
695
- let archiveUrl = ''
696
- let stored = item
697
- let firstAttempt = true
698
- await this.#transaction(async () => {
699
- const main = await this.#readControlled(this.path, signal)
700
- // On a retry, the item may be in the feed file already: another client repaired it from the archive.
701
- if (firstAttempt && main.doc.items.some(i => i.id == item.id))
702
- throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`)
703
- firstAttempt = false
704
- const doc: FeedDocument = { ...main.doc, _archive: { ...main.doc._archive } }
705
- const hasArchives = this.#archiveNumber(doc._archive!.archive_url) !== undefined
706
- if (!hasArchives && !this.#archivesWanted) {
707
- // A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
708
- archiveUrl = this.url
709
- const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)))
710
- stored = withIndex(item, indexed.next)
711
- doc._archive!.next_index = indexed.next + 1
712
- await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal)
713
- return
714
- }
715
- if (!hasArchives) {
716
- const started = await this.#startArchives(main, signal)
717
- if (started) {
718
- doc._archive!.archive_url = started.url
719
- doc.items = started.items
720
- }
721
- }
722
- const template = await this.#postUrlTemplate(signal)
723
- const added = await this.#addToArchive(main, doc, item, signal, template)
724
- archiveUrl = added.url
725
- stored = added.item
726
- doc._archive!.archive_url = added.url
727
- if (!hasArchives) {
728
- // The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
729
- // holds the counter.
730
- delete doc.next_url
731
- delete doc._archive!.next_index
732
- }
733
- doc.items = this.#newestItems(added.recent, doc.items, doc)
734
- await this.#writeMain(doc, main.etag, signal)
735
- })
736
- return this.#withMentions(options.mentions, this.#result(stored, archiveUrl), archiveUrl, stored, undefined, item => !!item)
737
- }
738
-
739
- /**
740
- * Gives every item of the feed without an index one (RFC-7 "Indexing an existing feed"), and sets the counter.
741
- * `addPost()` does this by itself before the first post to a feed that hasn't been indexed yet; call it to
742
- * index a feed without posting.
743
- */
744
- async assignIndexes(options: Signal = {}): Promise<void> {
745
- const signal = options.signal
746
- await this.#transaction(async () => {
747
- const main = await this.#readControlled(this.path, signal)
748
- const newest = this.#archiveNumber(main.doc._archive?.archive_url)
749
- if (newest === undefined) {
750
- const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
751
- if (indexed.changed || counterOf(main.doc) !== indexed.next)
752
- await this.#writeMain({ ...main.doc, items: indexed.items, _archive: { ...main.doc._archive, next_index: indexed.next } }, main.etag, signal)
753
- return
754
- }
755
- const archive = await this.#readArchive(this.#archivePath(newest), signal)
756
- if (archive && archive != 'foreign' && (counterOf(archive.doc) === undefined || archive.doc.items.some(item => itemIndex(item) === undefined)))
757
- await this.#indexArchives(main, signal)
758
- })
572
+ const { item, address } = await this.#post(this.#newItem(input), options.signal)
573
+ return this.#withMentions(options.mentions, this.#result(item, address), fileOf(address), item, undefined, found => !!found)
759
574
  }
760
575
 
761
576
  /**
762
- * Finds a post by id in the archives (or, for a handed-over feed without archives yet, in the feed file).
577
+ * Finds a post by id in the archives.
763
578
  * @returns undefined if there is no such post.
764
579
  */
765
580
  async getPost(id: string, options: Signal = {}): Promise<PostResult | undefined> {
766
581
  const main = await this.#read(this.path, options.signal)
767
- const found = main && await this.#find(main, id, options.signal)
768
- return found && this.#result(found.file.doc.items[found.index]!, this.#session.publicUrl(found.file.path))
582
+ if (!main) return
583
+ for await (const file of this.#chain(main, options.signal)) {
584
+ const item = file.doc.items.find(i => i.id == id)
585
+ if (item) return this.#result(item, `${this.#session.publicUrl(file.path)}#${encodeURIComponent(id)}`)
586
+ }
587
+ return
769
588
  }
770
589
 
771
590
  /**
@@ -785,70 +604,38 @@ export class PupsFeed {
785
604
  }
786
605
 
787
606
  /**
788
- * Edits a post in its archive, and in the feed file if it is among the newest items (RFC-7 "Editing and deleting
789
- * items"), and sets `date_modified`. `changes` is either an object (a value sets a field, `null` removes it), or
790
- * a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
791
- * function may run more than once.
607
+ * Edits a post (RFC-7 "Posting items"): reads it from its archive, applies `changes`, and sends it to the server,
608
+ * which replaces it in its archive and in the feed file and sets `date_modified`. `changes` is either an object (a
609
+ * value sets a field, `null` removes it), or a function that gets a copy of the item and returns the new item, or
610
+ * `undefined` to leave it unchanged. The post keeps its id and index.
792
611
  *
793
612
  * Apps should edit posts only when the owner asks them to, whichever app created them. With the option
794
- * `mentions`, everyone the old or the new version mentions is notified. A post of a feed with
795
- * archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
613
+ * `mentions`, everyone the old or the new version mentions is notified.
796
614
  * @throws {PupsError} `not_found`
797
615
  */
798
616
  async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: WithMentions = {}): Promise<PostResult> {
799
617
  const signal = options.signal
800
- let edit: { old: FeedItem; item: FeedItem; fileUrl: string } | undefined
801
- const result = await this.#transaction(async () => {
802
- edit = undefined
803
- const { main, file, index } = await this.#findWritable(id, signal)
804
- const old = file.doc.items[index]!
805
- const fileUrl = this.#session.publicUrl(file.path)
806
- const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes)
807
- if (!changed) return this.#result(old, fileUrl)
808
- const oldIndex = itemIndex(old)
809
- let item: FeedItem = { ...changed, id, date_modified: now() }
810
- // The index never changes (RFC-7 "Indexes").
811
- if (oldIndex !== undefined) item = withIndex(item, oldIndex)
812
- // A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
813
- if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._archive?.archive_url) !== undefined)
814
- item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal))
815
- if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
816
- const mainIndex = main.doc.items.findIndex(i => i.id == id)
817
- if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
818
- edit = { old, item, fileUrl }
819
- return this.#result(item, fileUrl)
820
- })
821
- const done = edit as typeof edit
822
- return done ? this.#withMentions(options.mentions, result, done.fileUrl, done.item, done.old, found => found?.date_modified == done.item.date_modified) : result
618
+ const current = await this.getPost(id, options)
619
+ if (!current) throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`)
620
+ const old = current.item
621
+ const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes)
622
+ if (!changed) return current
623
+ // The index names the post for the server (RFC-7 "Posting items"), and never changes.
624
+ const { _pups: _marker, ...rest } = changed
625
+ const { item, address } = await this.#post({ ...rest, id, _archive: { ...isObject(rest._archive) ? rest._archive : {}, ...old._archive } }, signal)
626
+ return this.#withMentions(options.mentions, this.#result(item, address), fileOf(address), item, old, found => found?.date_modified == item.date_modified)
823
627
  }
824
628
 
825
629
  /**
826
- * Deletes a post from its archive and from the feed file, which is then filled up again with the newest items
827
- * from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the post references
828
- * and no other post does; this reads all archives.
630
+ * Deletes a post (RFC-7 "Posting items"): the server removes it from its archive and from the feed file, which it
631
+ * fills up again from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the
632
+ * post references and no other post does; this reads all archives.
829
633
  * @returns the deleted item, and the public URLs of the deleted media files.
830
634
  * @throws {PupsError} `not_found`
831
635
  */
832
636
  async deletePost(id: string, options: WithMentions & { deleteMedia?: boolean } = {}): Promise<{ item: FeedItem; deletedMedia: string[]; mentions?: Promise<MentionReport[]> }> {
833
637
  const signal = options.signal
834
- let fileUrl = ''
835
- const item = await this.#transaction(async () => {
836
- const { main, file, index } = await this.#findWritable(id, signal)
837
- fileUrl = this.#session.publicUrl(file.path)
838
- const item = file.doc.items[index]!
839
- if (file != main) {
840
- await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal)
841
- // Fill the feed file up again from the archives, which no longer contain the item.
842
- const newest: FeedItem[] = []
843
- for await (const archive of this.#chain(main, signal)) {
844
- newest.push(...archive.doc.items.filter(i => i.id != id))
845
- if (newest.length >= this.#maxItems) break
846
- }
847
- await this.#writeMain({ ...main.doc, items: this.#newestItems(newest, [], main.doc) }, main.etag, signal)
848
- } else
849
- await this.#writeMain({ ...main.doc, items: main.doc.items.filter(i => i.id != id) }, main.etag, signal)
850
- return item
851
- })
638
+ const { item, address } = await this.#post({ id, _pups: { delete: true } }, signal)
852
639
  const deletedMedia: string[] = []
853
640
  if (options.deleteMedia) {
854
641
  const candidates = new Set(this.#mediaUrls(item))
@@ -860,7 +647,7 @@ export class PupsFeed {
860
647
  if (path && await this.#deleteQuietly(path, signal)) deletedMedia.push(url)
861
648
  }
862
649
  }
863
- const mentions = this.#sendMentions(options.mentions, fileUrl, undefined, item, found => !found)
650
+ const mentions = this.#sendMentions(options.mentions, fileOf(address), undefined, item, found => !found)
864
651
  return { item, deletedMedia, ...mentions ? { mentions } : {} }
865
652
  }
866
653
 
@@ -877,9 +664,9 @@ export class PupsFeed {
877
664
 
878
665
  /**
879
666
  * Submits a post that answers an item of an RFC-4 feed, e.g. a comment, to that feed's `_submissions.url`
880
- * (RFC-4 "Submitting"): `source` is the post's archive URL plus `#<id>`, `target` its `_source.inReplyTo`. Call it
881
- * after `addPost()` or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service
882
- * and what its `republish` means before the first submission.
667
+ * (RFC-4 "Submitting"): `source` is the post's address, `target` its `_source.inReplyTo`. Call it after `addPost()`
668
+ * or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service and what its
669
+ * `republish` means before the first submission.
883
670
  * @throws {PupsError} `not_found`; `invalid_request` if the post answers nothing; `unsupported` if the target
884
671
  * feed takes no submissions.
885
672
  * @deprecated Comments and group posts don't belong in a feed for readers (RFC-7 "Comment feeds"). Use
@@ -954,22 +741,13 @@ export class PupsFeed {
954
741
  // Not JSON: handled below.
955
742
  }
956
743
  if (!isFeedDocument(doc)) throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`)
957
- return { path, doc: upgradeArchiveFields(doc), etag: file.etag }
958
- }
959
-
960
- /** Reads a file that must exist and carry the `_pups` marker. */
961
- async #readControlled(path: string, signal?: AbortSignal): Promise<Loaded> {
962
- const loaded = await this.#read(path, signal)
963
- if (!loaded)
964
- throw new PupsError('not_found', path == this.path ? `There is no feed at ${path} yet. Set it up with create().` : `${path} doesn't exist.`)
965
- if (!isControlled(loaded.doc)) throw notControlled(path)
966
- return loaded
744
+ return { path, doc, etag: file.etag }
967
745
  }
968
746
 
969
747
  /**
970
748
  * The files that hold all items: the archives from `_archive.archive_url` along `next_url`, as far as they are files
971
- * on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
972
- * the pages its `next_url` names.
749
+ * on this server. A feed without archives (handed over, not written yet) holds its items in the feed file and the
750
+ * pages its `next_url` names.
973
751
  */
974
752
  async *#chain(main: Loaded, signal?: AbortSignal): AsyncGenerator<Loaded> {
975
753
  const visited = new Set<string>([main.path])
@@ -994,301 +772,52 @@ export class PupsFeed {
994
772
  }
995
773
  }
996
774
 
997
- async #find(main: Loaded, id: string, signal?: AbortSignal): Promise<Found | undefined> {
998
- for await (const file of this.#chain(main, signal)) {
999
- const index = file.doc.items.findIndex(item => item.id == id)
1000
- if (index >= 0) return { main, file, index }
1001
- }
1002
- return
1003
- }
1004
-
1005
- async #findWritable(id: string, signal?: AbortSignal): Promise<Found> {
1006
- const main = await this.#readControlled(this.path, signal)
1007
- const found = await this.#find(main, id, signal)
1008
- if (!found) throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`)
1009
- if (!isControlled(found.file.doc)) throw notControlled(found.file.path)
1010
- return found
1011
- }
1012
-
1013
775
  // Writing
1014
776
 
1015
- /** Runs `operation` again when another client changed a file in between, up to `maxAttempts` times. */
1016
- async #transaction<T>(operation: () => Promise<T>): Promise<T> {
1017
- for (let attempt = 1; ; attempt++)
1018
- try {
1019
- return await operation()
1020
- } catch (e) {
1021
- if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts) throw e
1022
- }
1023
- }
1024
-
1025
- /**
1026
- * Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
1027
- * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). A feed with archives gets the archive template
1028
- * and size of RFC-13, and its optional `next_url` is kept equal to `archive_url` (RFC-7 "Reading").
1029
- */
1030
- async #writeMain(doc: FeedDocument, etag: string, signal?: AbortSignal): Promise<FeedDocument> {
1031
- const { author, ...rest } = doc
1032
- const fixed: FeedDocument = {
1033
- ...rest,
1034
- version: JSON_FEED_VERSION,
1035
- home_page_url: this.#session.me,
1036
- feed_url: this.url,
1037
- user_comment: mainComment,
1038
- }
1039
- if (author !== undefined && fixed.authors === undefined) fixed.authors = [author as FeedAuthor]
1040
- const archiveUrl = fixed._archive?.archive_url
1041
- if (fixed._archive) fixed._archive = { about: ARCHIVE_SPEC, ...fixed._archive }
1042
- if (this.#archiveNumber(archiveUrl) !== undefined) {
1043
- fixed._archive = { ...fixed._archive, archive_template: this.#archiveTemplate(), archive_size: this.#archiveSize }
1044
- if (fixed.next_url !== undefined) fixed.next_url = archiveUrl
1045
- }
1046
- await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal })
1047
- return fixed
1048
- }
1049
-
1050
- /**
1051
- * Writes an archive with `items`, and with the counter `next_index` if given. An archive of an earlier draft gets its
1052
- * `_archive` fields and comment of RFC-13 (`number`, `updates_url`).
1053
- */
1054
- async #writeArchive(archive: Loaded, items: FeedItem[], signal?: AbortSignal, nextIndex?: number) {
1055
- const n = this.#archiveNumber(this.#session.publicUrl(archive.path))
1056
- const fields: ArchiveFields = { about: ARCHIVE_SPEC, ...archive.doc._archive, updates_url: this.url, ...n === undefined ? {} : { number: n } }
1057
- if (nextIndex !== undefined) fields.next_index = nextIndex
1058
- const doc: FeedDocument = { ...archive.doc, user_comment: archiveComment(this.url), items, _archive: fields }
1059
- await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal })
1060
- }
1061
-
1062
- /**
1063
- * The items of the feed file: the newest archive items first (which also repairs items an interrupted post wrote
1064
- * only into the archive), then the other items of the feed file, at most `maxItems`, fewer if `maxBytes` is set
1065
- * and exceeded, but at least 10.
1066
- */
1067
- #newestItems(recent: FeedItem[], current: FeedItem[], doc: FeedDocument): FeedItem[] {
1068
- const ids = new Set(recent.map(item => item.id))
1069
- const items = [...recent, ...current.filter(item => !ids.has(item.id))].slice(0, this.#maxItems)
1070
- if (this.#maxBytes)
1071
- while (items.length > minFeedItems && byteLength(serialize({ ...doc, items })) > this.#maxBytes) items.pop()
1072
- return items
1073
- }
1074
-
1075
- // Archives
1076
-
1077
- #archivePath(n: number) {
1078
- return `${this.directory}feed.${String(n).padStart(6, '0')}.json`
1079
- }
1080
-
1081
- #archiveUrl(n: number) {
1082
- return this.#session.publicUrl(this.#archivePath(n))
1083
- }
1084
-
1085
- /** `_archive.archive_template` (RFC-13): the archive URL with `{number}` for the number. */
1086
- #archiveTemplate() {
1087
- return this.#archiveUrl(0).replace(/000000\.json$/, '{number}.json')
1088
- }
1089
-
1090
- /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
1091
- #archiveNumber(url: string | undefined): number | undefined {
1092
- const path = url && pathFromPublicUrl(this.#session.server, url)
1093
- if (!path?.startsWith(this.directory)) return
1094
- const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length))
1095
- return match ? Number(match[1]) : undefined
1096
- }
1097
-
1098
- /**
1099
- * A new archive with the feed fields of the feed file (RFC-13 "Feed fields of an archive"), except `_submissions`:
1100
- * whether a feed accepts comments is said by its feed file alone.
1101
- */
1102
- #newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, nextIndex?: number): FeedDocument {
1103
- const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, _archive, _submissions: _s, ...fields } = main
1104
- const podcast = fields._podcast
1105
- if (isObject(podcast) && 'liveItems' in podcast) {
1106
- const { liveItems: _live, ...rest } = podcast
1107
- fields._podcast = rest
1108
- }
1109
- return {
1110
- ...fields,
1111
- version: JSON_FEED_VERSION,
1112
- home_page_url: this.#session.me,
1113
- feed_url: this.#archiveUrl(n),
1114
- user_comment: archiveComment(this.url),
1115
- ...nextUrl ? { next_url: nextUrl } : {},
1116
- items,
1117
- _pups: { about: PUPS_FEED_SPEC, ..._pups, pupsControlled: true },
1118
- _archive: { about: ARCHIVE_SPEC, updates_url: this.url, number: n, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
1119
- }
1120
- }
1121
-
1122
- async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal, nextIndex?: number) {
1123
- await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl, nextIndex)), { contentType: FEED_CONTENT_TYPE, signal })
1124
- }
1125
-
1126
- /**
1127
- * Reads an archive for writing.
1128
- * @returns undefined if it doesn't exist, 'foreign' if it exists but is no PUPS archive.
1129
- */
1130
- async #readArchive(path: string, signal?: AbortSignal): Promise<Loaded | 'foreign' | undefined> {
777
+ /** Sends an item to the server (RFC-7 "Posting items"). */
778
+ async #post(item: Record<string, unknown>, signal?: AbortSignal): Promise<Posted> {
779
+ this.#checkKept()
1131
780
  try {
1132
- const loaded = await this.#read(path, signal)
1133
- return loaded && !isControlled(loaded.doc) ? 'foreign' : loaded
781
+ return posted((await this.#session.post(this.path, item, { signal })).body, this.path)
1134
782
  } catch (e) {
1135
- if (isPupsError(e, 'invalid_feed')) return 'foreign'
783
+ if (isPupsError(e, 'not_pups_controlled')) throw notControlled(this.path)
784
+ if (isPupsError(e, 'not_found') && !await this.#session.get(this.path, { signal }))
785
+ throw new PupsError('not_found', `There is no feed at ${this.path} yet. Set it up with create().`, { cause: e })
1136
786
  throw e
1137
787
  }
1138
788
  }
1139
789
 
1140
790
  /**
1141
- * Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
1142
- * archives"). The items get indexes first, and the newest archive the counter. The oldest archive continues the
1143
- * feed's `next_url` chain.
1144
- * @returns the URL of the newest archive and the feed's items with their indexes, or undefined if the feed has no
1145
- * items.
791
+ * Changes the feed file's fields with `change` and writes it with `If-Match`; reads it again and repeats when
792
+ * someone else wrote in between, up to `maxAttempts` times. The server keeps the items and the archive fields.
793
+ * @returns the feed as written.
1146
794
  */
1147
- async #startArchives(main: Loaded, signal?: AbortSignal): Promise<{ url: string; items: FeedItem[] } | undefined> {
1148
- const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
1149
- const oldestFirst = [...indexed.items].reverse()
1150
- const count = Math.ceil(oldestFirst.length / this.#archiveSize)
1151
- let url: string | undefined
1152
- for (let n = 0; n < count; n++) {
1153
- const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse()
1154
- const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url
1155
- const nextIndex = n == count - 1 ? indexed.next : undefined
795
+ async #change(change: (doc: FeedDocument) => void, signal?: AbortSignal): Promise<FeedDocument> {
796
+ for (let attempt = 1; ; attempt++) {
797
+ const main = await this.#read(this.path, signal)
798
+ if (!main) throw new PupsError('not_found', `There is no feed at ${this.path} yet. Set it up with create().`)
799
+ if (!isControlled(main.doc)) throw notControlled(this.path)
800
+ const doc = clone(main.doc)
801
+ change(doc)
1156
802
  try {
1157
- await this.#createArchive(n, main.doc, items, nextUrl, signal, nextIndex)
803
+ await this.#session.replace(this.path, serialize(doc), main.etag, { contentType: FEED_CONTENT_TYPE, signal })
804
+ return doc
1158
805
  } catch (e) {
1159
- if (!isPupsError(e, 'precondition_failed')) throw e
1160
- // Left behind by an interrupted start: complete it, as long as it holds only these items.
1161
- const existing = await this.#readArchive(this.#archivePath(n), signal)
1162
- const ids = new Set(items.map(item => item.id))
1163
- if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
1164
- throw new PupsError('conflict', `${this.#archivePath(n)} exists already, but ${this.path} has no archive_url. Remove the file, or set _archive.archive_url (RFC-7, Starting the archives).`)
1165
- await this.#writeArchive(existing, items, signal, nextIndex)
806
+ if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts) throw e
1166
807
  }
1167
- url = this.#archiveUrl(n)
1168
- }
1169
- return url ? { url, items: indexed.items } : undefined
1170
- }
1171
-
1172
- /**
1173
- * Indexes a feed with archives whose newest archive has no counter, or items without an index (RFC-7 "Indexing an
1174
- * existing feed"): gives every archived item without an index one, the oldest first, writes the changed archives
1175
- * from the oldest to the newest, the newest with the counter, and then the feed file's copies.
1176
- */
1177
- async #indexArchives(main: Loaded, signal?: AbortSignal): Promise<void> {
1178
- const files: Loaded[] = []
1179
- for await (const file of this.#chain(main, signal)) {
1180
- // Pages behind the oldest archive of a handed-over feed are never written, and keep their items unindexed.
1181
- if (file == main || !isControlled(file.doc)) break
1182
- files.push(file)
1183
- }
1184
- if (!files.length) return
1185
- let next = nextFree(files.flatMap(file => file.doc.items), ...files.map(file => counterOf(file.doc)))
1186
- const indexes = new Map<string, number>()
1187
- for (const file of [...files].reverse()) {
1188
- const indexed = indexItems(file.doc.items, next)
1189
- next = indexed.next
1190
- for (const item of indexed.items) indexes.set(item.id, itemIndex(item)!)
1191
- const newest = file == files[0]
1192
- if (indexed.changed || (newest && counterOf(file.doc) !== next)) await this.#writeArchive(file, indexed.items, signal, newest ? next : undefined)
1193
808
  }
1194
- let changed = false
1195
- const items = main.doc.items.map(item => {
1196
- const index = indexes.get(item.id)
1197
- if (index === undefined || itemIndex(item) === index) return item
1198
- changed = true
1199
- return withIndex(item, index)
1200
- })
1201
- if (changed) await this.#writeMain({ ...main.doc, items }, main.etag, signal)
1202
809
  }
1203
810
 
1204
- /**
1205
- * Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
1206
- * "Posting"). Writes only archives; the caller writes the feed file afterwards.
1207
- * The item gets its index from the archive's counter (RFC-7 "Indexes"); a newest archive without a counter is
1208
- * indexed first, and the post then starts again.
1209
- * @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
1210
- */
1211
- async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal, template?: string): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
1212
- const place = (index: number) => this.#withPostUrl(withIndex(item, index), index, template)
1213
- const newest = this.#archiveNumber(doc._archive?.archive_url)
1214
- let previous: FeedItem[] = []
1215
- // The index for the item if it goes into a new archive.
1216
- let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined)
1217
- if (newest !== undefined) {
1218
- const existing = await this.#readArchive(this.#archivePath(newest), signal)
1219
- if (!existing) {
1220
- // The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
1221
- const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined
1222
- if (before && before != 'foreign') next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc))
1223
- const stored = place(next)
1224
- await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1)
1225
- return { url: this.#archiveUrl(newest), recent: [stored], item: stored }
1226
- }
1227
- if (existing != 'foreign') {
1228
- if (counterOf(existing.doc) === undefined) {
1229
- await this.#indexArchives(main, signal)
1230
- throw conflict(`${this.path} was indexed, so it`)
1231
- }
1232
- // Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
1233
- const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)))
1234
- const copy = indexed.items.find(i => i.id == item.id)
1235
- const stored = place(copy ? itemIndex(copy)! : indexed.next)
1236
- const merged = mergeItems(indexed.items, [stored])
1237
- if (merged.length <= this.#archiveSize) {
1238
- await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
1239
- return { url: this.#archiveUrl(newest), recent: merged, item: stored }
1240
- }
1241
- if (indexed.changed) await this.#writeArchive(existing, indexed.items, signal, indexed.next)
1242
- previous = indexed.items
1243
- next = indexed.next
1244
- }
1245
- }
1246
- // The archive before the new one: the newest, or for a feed without archives the end of its old chain.
1247
- const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest)
1248
- for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
1249
- const stored = place(next)
1250
- try {
1251
- await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1)
1252
- return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored }
1253
- } catch (e) {
1254
- if (!isPupsError(e, 'precondition_failed')) throw e
1255
- }
1256
- // The archive exists: left behind by an interrupted client, or created by another client just now.
1257
- const existing = await this.#readArchive(this.#archivePath(n), signal)
1258
- if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
1259
- const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next))
1260
- const copy = indexed.items.find(i => i.id == item.id)
1261
- const added = place(copy ? itemIndex(copy)! : indexed.next)
1262
- const merged = mergeItems(indexed.items, [added])
1263
- if (merged.length <= this.#archiveSize) {
1264
- await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
1265
- return { url: this.#archiveUrl(n), recent: [...merged, ...previous], item: added }
1266
- }
1267
- }
1268
- const current = await this.#session.get(this.path, { signal })
1269
- if (current?.etag != main.etag) throw conflict(this.path)
1270
- }
1271
- throw new PupsError('conflict', `No free archive number in ${this.directory}.`)
811
+ /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
812
+ #archiveNumber(url: string | undefined): number | undefined {
813
+ const path = url && pathFromPublicUrl(this.#session.server, url)
814
+ if (!path?.startsWith(this.directory)) return
815
+ const match = /^feed\.(\d{6,})\.json$/.exec(path.slice(this.directory.length))
816
+ return match ? Number(match[1]) : undefined
1272
817
  }
1273
818
 
1274
819
  // Items and media
1275
820
 
1276
- /** The site's post URL template from `host-meta.json`, read once; undefined if there is none or it can't be read. */
1277
- #postUrlTemplate(signal?: AbortSignal): Promise<string | undefined> {
1278
- if (!this.#postUrls) return Promise.resolve(undefined)
1279
- this.#template ??= this.#session.hostMeta.get({ signal })
1280
- .then(doc => doc.properties?.[POST_URL_TEMPLATE])
1281
- .then(template => validTemplate(template) ? template : undefined, () => undefined)
1282
- return this.#template
1283
- }
1284
-
1285
- /** The item with the `url` from the post URL template (RFC-7 "Post URLs"), unless it has one. */
1286
- #withPostUrl(item: FeedItem, index: number, template?: string): FeedItem {
1287
- if (!template || item.url) return item
1288
- const vars: Record<string, string> = { feed: this.path.slice(1, -'.json'.length), index: String(index), id: encodeURIComponent(item.id) }
1289
- return { ...item, url: template.replace(/\{(feed|index|id)\}/g, (_, name: string) => vars[name]!) }
1290
- }
1291
-
1292
821
  #newItem(input: PostInput): FeedItem {
1293
822
  const { id, markdown, date_published, ...fields } = input
1294
823
  if (id !== undefined && (typeof id != 'string' || !id))
@@ -1301,13 +830,12 @@ export class PupsFeed {
1301
830
  if (markdown !== undefined) this.#setMarkdown(item, markdown)
1302
831
  if (item.content_html === undefined && item.content_text === undefined)
1303
832
  throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).')
1304
- // The index is given out when the item is added (RFC-13 "Indexes").
1305
- for (const key of ['_archive', '_pups'] as const) {
1306
- const value = item[key]
1307
- if (!isObject(value)) continue
1308
- const { index: _index, ...rest } = value
1309
- if (Object.keys(rest).length) item[key] = rest
1310
- else delete item[key]
833
+ // An item with an index names an existing item; the server gives new items theirs (RFC-7 "Posting items").
834
+ delete item._pups
835
+ if (isObject(item._archive)) {
836
+ const { index: _index, ...rest } = item._archive
837
+ if (Object.keys(rest).length) item._archive = rest
838
+ else delete item._archive
1311
839
  }
1312
840
  return item
1313
841
  }
@@ -1339,9 +867,9 @@ export class PupsFeed {
1339
867
  if (item.content_html === undefined) item.content_text = markdown
1340
868
  }
1341
869
 
1342
- #result(item: FeedItem, fileUrl: string): PostResult {
870
+ #result(item: FeedItem, address: string): PostResult {
1343
871
  const index = itemIndex(item)
1344
- return { id: item.id, ...index === undefined ? {} : { index }, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` }
872
+ return { id: item.id, ...index === undefined ? {} : { index }, item, url: address }
1345
873
  }
1346
874
 
1347
875
  /**
@@ -1385,14 +913,11 @@ export class PupsFeed {
1385
913
  let old: unknown
1386
914
  let doc: FeedDocument
1387
915
  try {
1388
- doc = await this.#transaction(async () => {
1389
- const main = await this.#readControlled(this.path, signal)
1390
- old = main.doc[field]
1391
- const changed = { ...main.doc }
1392
- if (uploaded) changed[field] = uploaded.url
1393
- else delete changed[field]
1394
- return this.#writeMain(changed, main.etag, signal)
1395
- })
916
+ doc = await this.#change(doc => {
917
+ old = doc[field]
918
+ if (uploaded) doc[field] = uploaded.url
919
+ else delete doc[field]
920
+ }, signal)
1396
921
  } catch (e) {
1397
922
  if (uploaded) await this.#deleteQuietly(uploaded.path)
1398
923
  throw e
@@ -1423,6 +948,11 @@ export class PupsFeed {
1423
948
  throw new PupsError('invalid_request', `"${key}" is not a feed field the owner can set. Use title, description, authors, language, expired or an extension starting with "_".`)
1424
949
  }
1425
950
 
951
+ #checkKept() {
952
+ if (!this.#session.server.keptFeeds)
953
+ throw new PupsError('unsupported', `This PUPS server doesn't keep feeds: its configuration has no "kept_feeds": true (RFC-7, Server requirements).`)
954
+ }
955
+
1426
956
  #checkWritable() {
1427
957
  if (!this.writable)
1428
958
  throw new PupsError('insufficient_scope', `Writing ${this.path} needs the scopes ${this.scopes.join(' ')} (RFC-7, Server requirements).`)