pups-client 0.4.0 → 0.6.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/dist/feed.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { isPupsError, PupsError } from './errors.js';
2
2
  import { fileTypes } from './file-types.js';
3
3
  import { pathFromPublicUrl } from './paths.js';
4
- import { randomString } from './util.js';
4
+ import { itemHandles } from './handles.js';
5
+ import { isObject, randomString } from './util.js';
5
6
  /** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
6
7
  export const FEED_REL = 'https://bigwide.net/ns/feed';
7
8
  /**
@@ -11,20 +12,23 @@ export const FEED_REL = 'https://bigwide.net/ns/feed';
11
12
  export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template';
12
13
  /** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
13
14
  export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md';
15
+ /** The `about` of the `_archive` object: RFC-13 (JSON Feed Archives). Not its final location either. */
16
+ export const ARCHIVE_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-13-JSON-Feed-Archives.md';
14
17
  const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md';
18
+ const RFC4_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-4-Feed-Submissions.md';
15
19
  const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1';
16
20
  const FEED_CONTENT_TYPE = 'application/feed+json';
17
21
  const maxArchiveNumber = 999_999;
18
22
  /** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
19
23
  const minFeedItems = 10;
20
- 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 _pups.archive_url, all items are in the archives, starting with the one there.`;
21
- const archiveComment = (feedUrl) => `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 _pups.updates_url, older ones are in the archive at next_url.`;
24
+ 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.`;
25
+ const archiveComment = (feedUrl) => `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.`;
22
26
  /** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
23
27
  const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
24
28
  /** The main feed's media directories in `/feed/`, which therefore can't be feed names. */
25
29
  const mainMediaFolders = ['images', 'media'];
26
30
  /** Top-level fields that are fixed or managed by RFC-7, and can't be set through `create()` or `updateSettings()`. */
27
- const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', 'icon', 'favicon']);
31
+ const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', '_archive', 'icon', 'favicon']);
28
32
  /** The scopes an app needs to write a feed: the feed file and the feed directory (RFC-7 "Server requirements"). */
29
33
  export function feedScopes(name) {
30
34
  const { path, directory } = feedPaths(name);
@@ -39,7 +43,6 @@ function feedPaths(name) {
39
43
  throw new PupsError('invalid_request', `"${name}" can't be a feed name: /feed/${name}/ and its files belong to the main feed (RFC-7, Named feeds).`);
40
44
  return { path: `/feed/${name}.json`, directory: `/feed/${name}/` };
41
45
  }
42
- const isObject = (value) => !!value && typeof value == 'object' && !Array.isArray(value);
43
46
  const isFeedDocument = (value) => isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
44
47
  && Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string');
45
48
  const isControlled = (doc) => doc._pups?.pupsControlled === true;
@@ -56,12 +59,42 @@ function mergeItems(existing, incoming) {
56
59
  const present = new Set(existing.map(item => item.id));
57
60
  return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)];
58
61
  }
59
- /** The index of an item (RFC-7 "Indexes"), or undefined if it has none. */
62
+ /** The index of an item (RFC-13 "Indexes"), also from `_pups` of earlier drafts, or undefined if it has none. */
60
63
  export function itemIndex(item) {
61
- const index = isObject(item._pups) ? item._pups.index : undefined;
64
+ const index = isObject(item._archive) && item._archive.index !== undefined ? item._archive.index : isObject(item._pups) ? item._pups.index : undefined;
62
65
  return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined;
63
66
  }
64
- const withIndex = (item, index) => ({ ...item, _pups: { ...isObject(item._pups) ? item._pups : {}, index } });
67
+ const withIndex = (item, index) => ({ ...item, _archive: { ...isObject(item._archive) ? item._archive : {}, index } });
68
+ /** The fields of RFC-13 that earlier drafts of RFC-7 kept in `_pups`. */
69
+ const legacyArchiveFields = ['archive_url', 'updates_url', 'next_index'];
70
+ /**
71
+ * Moves the fields that earlier drafts kept in `_pups` into `_archive` (RFC-13 "Earlier drafts"), in the file and its
72
+ * items, where `_archive` doesn't have them already. Changes `doc`.
73
+ */
74
+ function upgradeArchiveFields(doc) {
75
+ const move = (from, to, keys) => {
76
+ for (const key of keys)
77
+ if (key in from) {
78
+ if (to[key] === undefined)
79
+ to[key] = from[key];
80
+ delete from[key];
81
+ }
82
+ };
83
+ if (isObject(doc._pups) && legacyArchiveFields.some(key => key in doc._pups)) {
84
+ const archive = { about: ARCHIVE_SPEC, ...isObject(doc._archive) ? doc._archive : {} };
85
+ move(doc._pups, archive, legacyArchiveFields);
86
+ doc._archive = archive;
87
+ }
88
+ for (const item of doc.items)
89
+ if (isObject(item._pups) && 'index' in item._pups) {
90
+ const archive = isObject(item._archive) ? item._archive : {};
91
+ move(item._pups, archive, ['index']);
92
+ item._archive = archive;
93
+ if (!Object.keys(item._pups).length)
94
+ delete item._pups;
95
+ }
96
+ return doc;
97
+ }
65
98
  /** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
66
99
  function validTemplate(template) {
67
100
  if (typeof template != 'string' || !/\{(index|id)\}/.test(template))
@@ -73,9 +106,9 @@ function validTemplate(template) {
73
106
  return false;
74
107
  }
75
108
  }
76
- /** The counter `_pups.next_index` of a file, if it has a valid one. */
109
+ /** The counter `_archive.next_index` of a file, if it has a valid one. */
77
110
  function counterOf(doc) {
78
- const next = doc._pups?.next_index;
111
+ const next = doc._archive?.next_index;
79
112
  return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined;
80
113
  }
81
114
  /** The next free index: above every index of `items`, and at least each of `counters`. */
@@ -136,6 +169,7 @@ export class PupsFeed {
136
169
  #maxBytes;
137
170
  #maxAttempts;
138
171
  #postUrls;
172
+ #mentions;
139
173
  #template;
140
174
  /** @internal Use `session.feed()`. */
141
175
  constructor(session, name, options = {}) {
@@ -150,6 +184,7 @@ export class PupsFeed {
150
184
  this.#maxBytes = options.maxBytes;
151
185
  this.#maxAttempts = options.maxAttempts ?? 8;
152
186
  this.#postUrls = options.postUrls ?? true;
187
+ this.#mentions = options.mentions === true ? session.mentions : options.mentions || undefined;
153
188
  if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
154
189
  throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.');
155
190
  }
@@ -279,6 +314,49 @@ export class PupsFeed {
279
314
  setFavicon(media, options = {}) {
280
315
  return this.#setImage('favicon', media, options.signal);
281
316
  }
317
+ /** Whether the PUPS server can receive comments on the feed's posts (`comment_endpoint`, RFC-6 "Built-in receiver"). */
318
+ get commentsAvailable() {
319
+ return !!this.#session.server.commentEndpoint;
320
+ }
321
+ /** Whether the feed accepts comments, and through whom; `doc` is the feed file, e.g. from `load()`. */
322
+ comments(doc) {
323
+ const submissions = doc._submissions;
324
+ if (!isObject(submissions))
325
+ return 'off';
326
+ const endpoint = this.#session.server.commentEndpoint;
327
+ return endpoint && submissions.url == endpoint ? 'pups' : 'other';
328
+ }
329
+ /**
330
+ * Lets readers comment on the feed's posts through the PUPS server, which puts the comments into the owner's inbox
331
+ * (RFC-6 "Built-in receiver"): writes RFC-4 `_submissions` into the feed file, with `comment_endpoint` as `url`,
332
+ * the comments policy (RFC-4's defaults for `title`, `minLength` and `maxLength`, overridden by `policy`) and
333
+ * `republish: "no"`. Replaces the `_submissions` of another service; check `comments()` first and ask the owner.
334
+ * Single posts are closed with `_commenting: { allowComments: false }` (RFC-4).
335
+ * @throws {PupsError} `unsupported` if the server has no `comment_endpoint`.
336
+ */
337
+ async enableComments(settings = {}, options = {}) {
338
+ const url = this.#session.server.commentEndpoint;
339
+ if (!url)
340
+ throw new PupsError('unsupported', 'This PUPS server doesn\'t receive comments: its configuration has no comment_endpoint (RFC-6, Built-in receiver).');
341
+ return this.#setSubmissions({
342
+ about: RFC4_URL,
343
+ url,
344
+ ...settings.tos ? { tos: settings.tos } : {},
345
+ policies: { comments: { title: 'none', minLength: 2, maxLength: 2000, ...settings.policy } },
346
+ republish: 'no',
347
+ }, options.signal);
348
+ }
349
+ /** Closes the feed for comments: removes `_submissions` from the feed file, whichever service it names. */
350
+ disableComments(options = {}) {
351
+ return this.#setSubmissions(undefined, options.signal);
352
+ }
353
+ #setSubmissions(submissions, signal) {
354
+ return this.#transaction(async () => {
355
+ const main = await this.#readControlled(this.path, signal);
356
+ const { _submissions: _old, ...doc } = main.doc;
357
+ return this.#writeMain(submissions ? { ...doc, _submissions: submissions } : doc, main.etag, signal);
358
+ });
359
+ }
282
360
  /**
283
361
  * Uploads an image, audio or video file into the feed directory under a new, unique name, by default
284
362
  * `images/<year>/…` for images and `media/<year>/…` for everything else. Reference it from a post by its `url`.
@@ -300,6 +378,8 @@ export class PupsFeed {
300
378
  * media with `uploadMedia()` before posting.
301
379
  * In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
302
380
  * has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
381
+ * With the option `mentions`, the domains the post names and the author of the item it answers are notified
382
+ * (RFC-11) once the post is visible; see `PostResult.mentions`.
303
383
  * @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
304
384
  * archives, the feed file's URL plus `#<id>`, valid while the post is among the newest. The post's page, if it
305
385
  * has one, is `item.url`.
@@ -316,21 +396,21 @@ export class PupsFeed {
316
396
  if (firstAttempt && main.doc.items.some(i => i.id == item.id))
317
397
  throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`);
318
398
  firstAttempt = false;
319
- const doc = { ...main.doc, _pups: { ...main.doc._pups } };
320
- const hasArchives = this.#archiveNumber(doc._pups.archive_url) !== undefined;
399
+ const doc = { ...main.doc, _archive: { ...main.doc._archive } };
400
+ const hasArchives = this.#archiveNumber(doc._archive.archive_url) !== undefined;
321
401
  if (!hasArchives && !this.#archivesWanted) {
322
402
  // A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
323
403
  archiveUrl = this.url;
324
404
  const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)));
325
405
  stored = withIndex(item, indexed.next);
326
- doc._pups.next_index = indexed.next + 1;
406
+ doc._archive.next_index = indexed.next + 1;
327
407
  await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal);
328
408
  return;
329
409
  }
330
410
  if (!hasArchives) {
331
411
  const started = await this.#startArchives(main, signal);
332
412
  if (started) {
333
- doc._pups.archive_url = started.url;
413
+ doc._archive.archive_url = started.url;
334
414
  doc.items = started.items;
335
415
  }
336
416
  }
@@ -338,17 +418,17 @@ export class PupsFeed {
338
418
  const added = await this.#addToArchive(main, doc, item, signal, template);
339
419
  archiveUrl = added.url;
340
420
  stored = added.item;
341
- doc._pups.archive_url = added.url;
421
+ doc._archive.archive_url = added.url;
342
422
  if (!hasArchives) {
343
423
  // The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
344
424
  // holds the counter.
345
425
  delete doc.next_url;
346
- delete doc._pups.next_index;
426
+ delete doc._archive.next_index;
347
427
  }
348
428
  doc.items = this.#newestItems(added.recent, doc.items, doc);
349
429
  await this.#writeMain(doc, main.etag, signal);
350
430
  });
351
- return this.#result(stored, archiveUrl);
431
+ return this.#withMentions(options.mentions, this.#result(stored, archiveUrl), archiveUrl, stored, undefined, item => !!item);
352
432
  }
353
433
  /**
354
434
  * Gives every item of the feed without an index one (RFC-7 "Indexing an existing feed"), and sets the counter.
@@ -359,11 +439,11 @@ export class PupsFeed {
359
439
  const signal = options.signal;
360
440
  await this.#transaction(async () => {
361
441
  const main = await this.#readControlled(this.path, signal);
362
- const newest = this.#archiveNumber(main.doc._pups?.archive_url);
442
+ const newest = this.#archiveNumber(main.doc._archive?.archive_url);
363
443
  if (newest === undefined) {
364
444
  const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)));
365
445
  if (indexed.changed || counterOf(main.doc) !== indexed.next)
366
- await this.#writeMain({ ...main.doc, items: indexed.items, _pups: { ...main.doc._pups, next_index: indexed.next } }, main.etag, signal);
446
+ await this.#writeMain({ ...main.doc, items: indexed.items, _archive: { ...main.doc._archive, next_index: indexed.next } }, main.etag, signal);
367
447
  return;
368
448
  }
369
449
  const archive = await this.#readArchive(this.#archivePath(newest), signal);
@@ -381,7 +461,7 @@ export class PupsFeed {
381
461
  return found && this.#result(found.file.doc.items[found.index], this.#session.publicUrl(found.file.path));
382
462
  }
383
463
  /**
384
- * All posts, newest first: the archives from `_pups.archive_url` along `next_url` (for a feed without archives,
464
+ * All posts, newest first: the archives from `_archive.archive_url` along `next_url` (for a feed without archives,
385
465
  * the feed file and its `next_url` chain). Each post is returned once.
386
466
  */
387
467
  async *posts(options = {}) {
@@ -402,13 +482,16 @@ export class PupsFeed {
402
482
  * a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
403
483
  * function may run more than once.
404
484
  *
405
- * Apps should edit posts only when the owner asks them to, whichever app created them. A post of a feed with
485
+ * Apps should edit posts only when the owner asks them to, whichever app created them. With the option
486
+ * `mentions`, everyone the old or the new version mentions is notified. A post of a feed with
406
487
  * archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
407
488
  * @throws {PupsError} `not_found`
408
489
  */
409
490
  async editPost(id, changes, options = {}) {
410
491
  const signal = options.signal;
411
- return this.#transaction(async () => {
492
+ let edit;
493
+ const result = await this.#transaction(async () => {
494
+ edit = undefined;
412
495
  const { main, file, index } = await this.#findWritable(id, signal);
413
496
  const old = file.doc.items[index];
414
497
  const fileUrl = this.#session.publicUrl(file.path);
@@ -421,15 +504,18 @@ export class PupsFeed {
421
504
  if (oldIndex !== undefined)
422
505
  item = withIndex(item, oldIndex);
423
506
  // A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
424
- if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._pups?.archive_url) !== undefined)
507
+ if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._archive?.archive_url) !== undefined)
425
508
  item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal));
426
509
  if (file != main)
427
510
  await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal);
428
511
  const mainIndex = main.doc.items.findIndex(i => i.id == id);
429
512
  if (mainIndex >= 0)
430
513
  await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal);
514
+ edit = { old, item, fileUrl };
431
515
  return this.#result(item, fileUrl);
432
516
  });
517
+ const done = edit;
518
+ return done ? this.#withMentions(options.mentions, result, done.fileUrl, done.item, done.old, found => found?.date_modified == done.item.date_modified) : result;
433
519
  }
434
520
  /**
435
521
  * Deletes a post from its archive and from the feed file, which is then filled up again with the newest items
@@ -440,8 +526,10 @@ export class PupsFeed {
440
526
  */
441
527
  async deletePost(id, options = {}) {
442
528
  const signal = options.signal;
529
+ let fileUrl = '';
443
530
  const item = await this.#transaction(async () => {
444
531
  const { main, file, index } = await this.#findWritable(id, signal);
532
+ fileUrl = this.#session.publicUrl(file.path);
445
533
  const item = file.doc.items[index];
446
534
  if (file != main) {
447
535
  await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal);
@@ -471,7 +559,75 @@ export class PupsFeed {
471
559
  deletedMedia.push(url);
472
560
  }
473
561
  }
474
- return { item, deletedMedia };
562
+ const mentions = this.#sendMentions(options.mentions, fileUrl, undefined, item, found => !found);
563
+ return { item, deletedMedia, ...mentions ? { mentions } : {} };
564
+ }
565
+ /**
566
+ * Sends the RFC-11 mentions of a post now, e.g. to try again those that failed (see `Mentions.notifyAll()`). With
567
+ * `previous`, the version before an edit, also to the accounts that one mentioned.
568
+ * @throws {PupsError} `not_found`
569
+ */
570
+ async sendMentions(id, options = {}) {
571
+ const post = await this.getPost(id, options);
572
+ if (!post)
573
+ throw new PupsError('not_found', `The feed has no post with the id "${id}".`);
574
+ return this.#mentionSender.notifyAll({ source: post.url, item: post.item, previous: options.previous, me: this.#session.me }, options);
575
+ }
576
+ /**
577
+ * Submits a post that answers an item of an RFC-4 feed, e.g. a comment, to that feed's `_submissions.url`
578
+ * (RFC-4 "Submitting"): `source` is the post's archive URL plus `#<id>`, `target` its `_source.inReplyTo`. Call it
579
+ * after `addPost()` or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service
580
+ * and what its `republish` means before the first submission.
581
+ * @throws {PupsError} `not_found`; `invalid_request` if the post answers nothing; `unsupported` if the target
582
+ * feed takes no submissions.
583
+ */
584
+ async submit(id, options = {}) {
585
+ const post = await this.getPost(id, options);
586
+ if (!post)
587
+ throw new PupsError('not_found', `The feed has no post with the id "${id}".`);
588
+ const source = isObject(post.item._source) ? post.item._source : {};
589
+ if (typeof source.inReplyTo != 'string')
590
+ throw new PupsError('invalid_request', `The post "${id}" has no _source.inReplyTo, so it answers nothing (RFC-4).`);
591
+ return this.#session.mentions.submit(post.url, source.inReplyTo, options);
592
+ }
593
+ /**
594
+ * The RFC-11 mentions a post would send (see `Mentions.plan()`), e.g. to ask the author before posting:
595
+ *
596
+ * ```ts
597
+ * const planned = await feed.planMentions(input)
598
+ * const confirmed = planned.length && await askToNotify(planned) ? planned : false // the app's dialog
599
+ * await feed.addPost(input, { mentions: confirmed })
600
+ * ```
601
+ *
602
+ * For an edit, pass the post as it will be and the current version as `previous`; for a delete, only `previous`.
603
+ */
604
+ planMentions(post, options = {}) {
605
+ return this.#mentionSender.plan({ item: post, previous: options.previous, me: this.#session.me }, options);
606
+ }
607
+ get #mentionSender() {
608
+ return this.#mentions ?? this.#session.mentions;
609
+ }
610
+ /** The result with the RFC-11 mentions of the post, if the write sends them (see `#sendMentions()`). */
611
+ #withMentions(choice, result, fileUrl, item, previous, ready) {
612
+ const mentions = this.#sendMentions(choice, fileUrl, item, previous, ready);
613
+ return mentions ? { ...result, mentions } : result;
614
+ }
615
+ /**
616
+ * Sends the RFC-11 mentions of a post in the background, once its file at `fileUrl` is in the state `ready` wants:
617
+ * all, none, or the planned ones, as `choice` (default: the feed's option) says. Undefined if nothing is sent.
618
+ */
619
+ #sendMentions(choice, fileUrl, item, previous, ready) {
620
+ choice ??= !!this.#mentions;
621
+ const relevant = (i) => !!i && (itemHandles(i).length > 0 || (isObject(i._source) && typeof i._source.inReplyTo == 'string'));
622
+ if (Array.isArray(choice) ? !choice.length : !choice || !(relevant(item) || relevant(previous)))
623
+ return;
624
+ const mentions = this.#mentionSender;
625
+ const id = (item ?? previous).id;
626
+ const source = `${fileUrl}#${encodeURIComponent(id)}`;
627
+ return (async () => {
628
+ await mentions.waitForItem(fileUrl, id, ready);
629
+ return Array.isArray(choice) ? mentions.sendPlanned(source, choice) : mentions.notifyAll({ source, item, previous, me: this.#session.me });
630
+ })().catch(() => []);
475
631
  }
476
632
  // Reading
477
633
  /**
@@ -494,7 +650,7 @@ export class PupsFeed {
494
650
  }
495
651
  if (!isFeedDocument(doc))
496
652
  throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`);
497
- return { path, doc, etag: file.etag };
653
+ return { path, doc: upgradeArchiveFields(doc), etag: file.etag };
498
654
  }
499
655
  /** Reads a file that must exist and carry the `_pups` marker. */
500
656
  async #readControlled(path, signal) {
@@ -506,13 +662,13 @@ export class PupsFeed {
506
662
  return loaded;
507
663
  }
508
664
  /**
509
- * The files that hold all items: the archives from `_pups.archive_url` along `next_url`, as far as they are files
665
+ * The files that hold all items: the archives from `_archive.archive_url` along `next_url`, as far as they are files
510
666
  * on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
511
667
  * the pages its `next_url` names.
512
668
  */
513
669
  async *#chain(main, signal) {
514
670
  const visited = new Set([main.path]);
515
- const archive = main.doc._pups?.archive_url;
671
+ const archive = main.doc._archive?.archive_url;
516
672
  let file = main;
517
673
  let next = archive && this.#archiveNumber(archive) !== undefined ? archive : undefined;
518
674
  if (next)
@@ -570,8 +726,8 @@ export class PupsFeed {
570
726
  }
571
727
  /**
572
728
  * Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
573
- * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). The optional `next_url` of a feed with
574
- * archives is kept equal to `archive_url` (RFC-7 "Reading").
729
+ * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). A feed with archives gets the archive template
730
+ * and size of RFC-13, and its optional `next_url` is kept equal to `archive_url` (RFC-7 "Reading").
575
731
  */
576
732
  async #writeMain(doc, etag, signal) {
577
733
  const { author, ...rest } = doc;
@@ -584,14 +740,27 @@ export class PupsFeed {
584
740
  };
585
741
  if (author !== undefined && fixed.authors === undefined)
586
742
  fixed.authors = [author];
587
- if (fixed.next_url !== undefined && this.#archiveNumber(fixed._pups?.archive_url) !== undefined)
588
- fixed.next_url = fixed._pups.archive_url;
743
+ const archiveUrl = fixed._archive?.archive_url;
744
+ if (fixed._archive)
745
+ fixed._archive = { about: ARCHIVE_SPEC, ...fixed._archive };
746
+ if (this.#archiveNumber(archiveUrl) !== undefined) {
747
+ fixed._archive = { ...fixed._archive, archive_template: this.#archiveTemplate(), archive_size: this.#archiveSize };
748
+ if (fixed.next_url !== undefined)
749
+ fixed.next_url = archiveUrl;
750
+ }
589
751
  await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal });
590
752
  return fixed;
591
753
  }
592
- /** Writes an archive with `items`, and with the counter `next_index` if given. */
754
+ /**
755
+ * Writes an archive with `items`, and with the counter `next_index` if given. An archive of an earlier draft gets its
756
+ * `_archive` fields and comment of RFC-13 (`number`, `updates_url`).
757
+ */
593
758
  async #writeArchive(archive, items, signal, nextIndex) {
594
- const doc = nextIndex === undefined ? { ...archive.doc, items } : { ...archive.doc, items, _pups: { ...archive.doc._pups, next_index: nextIndex } };
759
+ const n = this.#archiveNumber(this.#session.publicUrl(archive.path));
760
+ const fields = { about: ARCHIVE_SPEC, ...archive.doc._archive, updates_url: this.url, ...n === undefined ? {} : { number: n } };
761
+ if (nextIndex !== undefined)
762
+ fields.next_index = nextIndex;
763
+ const doc = { ...archive.doc, user_comment: archiveComment(this.url), items, _archive: fields };
595
764
  await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal });
596
765
  }
597
766
  /**
@@ -614,6 +783,10 @@ export class PupsFeed {
614
783
  #archiveUrl(n) {
615
784
  return this.#session.publicUrl(this.#archivePath(n));
616
785
  }
786
+ /** `_archive.archive_template` (RFC-13): the archive URL with `{number}` for the number. */
787
+ #archiveTemplate() {
788
+ return this.#archiveUrl(0).replace(/000000\.json$/, '{number}.json');
789
+ }
617
790
  /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
618
791
  #archiveNumber(url) {
619
792
  const path = url && pathFromPublicUrl(this.#session.server, url);
@@ -622,10 +795,12 @@ export class PupsFeed {
622
795
  const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length));
623
796
  return match ? Number(match[1]) : undefined;
624
797
  }
625
- /** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
798
+ /**
799
+ * A new archive with the feed fields of the feed file (RFC-13 "Feed fields of an archive"), except `_submissions`:
800
+ * whether a feed accepts comments is said by its feed file alone.
801
+ */
626
802
  #newArchive(n, main, items, nextUrl, nextIndex) {
627
- const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main;
628
- const { archive_url: _archive, next_index: _counter, ...marker } = _pups ?? {};
803
+ const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, _archive, _submissions: _s, ...fields } = main;
629
804
  const podcast = fields._podcast;
630
805
  if (isObject(podcast) && 'liveItems' in podcast) {
631
806
  const { liveItems: _live, ...rest } = podcast;
@@ -639,7 +814,8 @@ export class PupsFeed {
639
814
  user_comment: archiveComment(this.url),
640
815
  ...nextUrl ? { next_url: nextUrl } : {},
641
816
  items,
642
- _pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
817
+ _pups: { about: PUPS_FEED_SPEC, ..._pups, pupsControlled: true },
818
+ _archive: { about: ARCHIVE_SPEC, updates_url: this.url, number: n, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
643
819
  };
644
820
  }
645
821
  async #createArchive(n, main, items, nextUrl, signal, nextIndex) {
@@ -686,7 +862,7 @@ export class PupsFeed {
686
862
  const existing = await this.#readArchive(this.#archivePath(n), signal);
687
863
  const ids = new Set(items.map(item => item.id));
688
864
  if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
689
- 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).`);
865
+ 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).`);
690
866
  await this.#writeArchive(existing, items, signal, nextIndex);
691
867
  }
692
868
  url = this.#archiveUrl(n);
@@ -739,7 +915,7 @@ export class PupsFeed {
739
915
  */
740
916
  async #addToArchive(main, doc, item, signal, template) {
741
917
  const place = (index) => this.#withPostUrl(withIndex(item, index), index, template);
742
- const newest = this.#archiveNumber(doc._pups?.archive_url);
918
+ const newest = this.#archiveNumber(doc._archive?.archive_url);
743
919
  let previous = [];
744
920
  // The index for the item if it goes into a new archive.
745
921
  let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined);
@@ -834,13 +1010,16 @@ export class PupsFeed {
834
1010
  this.#setMarkdown(item, markdown);
835
1011
  if (item.content_html === undefined && item.content_text === undefined)
836
1012
  throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).');
837
- // The index is given out when the item is added (RFC-7 "Indexes").
838
- if (isObject(item._pups)) {
839
- const { index: _index, ...marker } = item._pups;
840
- if (Object.keys(marker).length)
841
- item._pups = marker;
1013
+ // The index is given out when the item is added (RFC-13 "Indexes").
1014
+ for (const key of ['_archive', '_pups']) {
1015
+ const value = item[key];
1016
+ if (!isObject(value))
1017
+ continue;
1018
+ const { index: _index, ...rest } = value;
1019
+ if (Object.keys(rest).length)
1020
+ item[key] = rest;
842
1021
  else
843
- delete item._pups;
1022
+ delete item[key];
844
1023
  }
845
1024
  return item;
846
1025
  }