pups-client 0.7.0 → 0.9.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
@@ -7,7 +7,7 @@ import { isObject, randomString } from './util.js';
7
7
  export const FEED_REL = 'https://bigwide.net/ns/feed';
8
8
  /**
9
9
  * The site property in `host-meta.json` with the URL template of the pages that show single posts, e.g.
10
- * `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs", RFC-7 "Post URLs").
10
+ * `https://tim.example/p/{feed}/post/{index}` (RFC-6 "Post URLs"). The server fills it into new posts.
11
11
  */
12
12
  export const POST_URL_TEMPLATE = 'https://bigwide.net/ns/post-url-template';
13
13
  /** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
@@ -18,15 +18,12 @@ const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for
18
18
  const RFC4_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-4-Feed-Submissions.md';
19
19
  const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1';
20
20
  const FEED_CONTENT_TYPE = 'application/feed+json';
21
- const maxArchiveNumber = 999_999;
22
- /** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
23
- const minFeedItems = 10;
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.`;
26
21
  /** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
27
22
  const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
28
- /** The main feed's media directories in `/feed/`, which therefore can't be feed names. */
23
+ /** The main feed's media directories in `/feed/`. */
29
24
  const mainMediaFolders = ['images', 'media'];
25
+ /** Names in `/feed/` that belong to the main feed, its media and comment feeds, and therefore can't be feed names. */
26
+ const reservedNames = [...mainMediaFolders, 'comments'];
30
27
  /** Top-level fields that are fixed or managed by RFC-7, and can't be set through `create()` or `updateSettings()`. */
31
28
  const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', '_archive', 'icon', 'favicon']);
32
29
  /** The scopes an app needs to write a feed: the feed file and the feed directory (RFC-7 "Server requirements"). */
@@ -39,95 +36,23 @@ function feedPaths(name) {
39
36
  return { path: '/feed.json', directory: '/feed/' };
40
37
  if (!feedNamePattern.test(name))
41
38
  throw new PupsError('invalid_request', `"${name}" is not a valid feed name: use 1 to 40 lowercase letters, digits and "-", not starting or ending with "-" (RFC-7, Named feeds).`);
42
- if (mainMediaFolders.includes(name))
39
+ if (reservedNames.includes(name))
43
40
  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).`);
44
41
  return { path: `/feed/${name}.json`, directory: `/feed/${name}/` };
45
42
  }
46
43
  const isFeedDocument = (value) => isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
47
44
  && Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string');
48
45
  const isControlled = (doc) => doc._pups?.pupsControlled === true;
49
- const notControlled = (path) => 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).`);
50
- const conflict = (what) => new PupsError('precondition_failed', `${what} changed in the meantime.`);
46
+ const notControlled = (path) => 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).`);
51
47
  const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
52
48
  const clone = (value) => structuredClone(value);
53
49
  const serialize = (doc) => JSON.stringify(doc, null, 2);
54
50
  const byteLength = (text) => new TextEncoder().encode(text).length;
55
- const replaceAt = (array, index, value) => array.map((v, i) => i == index ? value : v);
56
- /** Adds `incoming` items at the top of `existing`; an item whose id is already there replaces the old copy instead. */
57
- function mergeItems(existing, incoming) {
58
- const byId = new Map(incoming.map(item => [item.id, item]));
59
- const present = new Set(existing.map(item => item.id));
60
- return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)];
61
- }
62
- /** The index of an item (RFC-13 "Indexes"), also from `_pups` of earlier drafts, or undefined if it has none. */
51
+ /** The index of an item (RFC-13 "Indexes"), or undefined if it has none. */
63
52
  export function itemIndex(item) {
64
- const index = isObject(item._archive) && item._archive.index !== undefined ? item._archive.index : isObject(item._pups) ? item._pups.index : undefined;
53
+ const index = isObject(item._archive) ? item._archive.index : undefined;
65
54
  return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined;
66
55
  }
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
- }
98
- /** A post URL template (RFC-6 "Post URLs"): an https URL with `{index}` or `{id}`. */
99
- function validTemplate(template) {
100
- if (typeof template != 'string' || !/\{(index|id)\}/.test(template))
101
- return false;
102
- try {
103
- return new URL(template.replace(/\{(feed|index|id)\}/g, 'x')).protocol == 'https:';
104
- }
105
- catch {
106
- return false;
107
- }
108
- }
109
- /** The counter `_archive.next_index` of a file, if it has a valid one. */
110
- function counterOf(doc) {
111
- const next = doc._archive?.next_index;
112
- return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined;
113
- }
114
- /** The next free index: above every index of `items`, and at least each of `counters`. */
115
- const nextFree = (items, ...counters) => Math.max(0, ...counters.filter((c) => c !== undefined), ...items.map(item => (itemIndex(item) ?? -1) + 1));
116
- /**
117
- * Gives the items without an index (newest first, as in a file) the next indexes from `next`, the oldest first
118
- * (RFC-7 "Items without an index").
119
- * @returns the items, and the counter after them.
120
- */
121
- function indexItems(items, next) {
122
- const result = [...items];
123
- let changed = false;
124
- for (let i = result.length - 1; i >= 0; i--)
125
- if (itemIndex(result[i]) === undefined) {
126
- result[i] = withIndex(result[i], next++);
127
- changed = true;
128
- }
129
- return { items: result, next, changed };
130
- }
131
56
  /** Every string inside `value`, deeply. */
132
57
  function* strings(value) {
133
58
  if (typeof value == 'string')
@@ -145,15 +70,24 @@ function extensionForType(type) {
145
70
  const entries = Object.entries(fileTypes);
146
71
  return entries.find(([, t]) => t.served == essence)?.[0] ?? entries.find(([, t]) => t.accepted.includes(essence))?.[0];
147
72
  }
73
+ /** The answer to a POST of an item, checked. */
74
+ function posted(body, path) {
75
+ if (!isObject(body) || !isObject(body.item) || typeof body.item.id != 'string' || typeof body.address != 'string')
76
+ throw new PupsError('server_error', `The server's answer to the POST to ${path} has no item and address (RFC-7, Posting items).`);
77
+ return { item: body.item, address: body.address };
78
+ }
79
+ /** The file part of an item's address. */
80
+ const fileOf = (address) => address.split('#')[0];
148
81
  /**
149
- * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json`, or a named feed
150
- * `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
82
+ * A feed on the owner's domain, kept by the PUPS server according to RFC-7: the main feed `/feed.json`, or a named
83
+ * feed `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
151
84
  * The main feed keeps its media in `/feed/images/` and `/feed/media/`, since the rest of `/feed/` belongs to the
152
85
  * named feeds.
153
86
  *
154
87
  * Get one from `session.feed()` or `session.feed('photos')`. The session needs the feed's scopes, see
155
- * {@link feedScopes}. All writes are safe against concurrent changes by other apps and the owner: they are
156
- * read-modify-write cycles with ETags, repeated when another client wrote in between.
88
+ * {@link feedScopes}. Posts are sent to the server one at a time, which gives them their index and puts them into
89
+ * the archives (RFC-13); changes of the feed's settings are read-modify-write cycles with ETags, repeated when
90
+ * another app wrote in between.
157
91
  */
158
92
  export class PupsFeed {
159
93
  /** The name of a named feed; undefined for the main feed. */
@@ -163,14 +97,8 @@ export class PupsFeed {
163
97
  /** The feed directory, e.g. `/feed/` or `/feed/photos/`. */
164
98
  directory;
165
99
  #session;
166
- #maxItems;
167
- #archiveSize;
168
- #archivesWanted;
169
- #maxBytes;
170
100
  #maxAttempts;
171
- #postUrls;
172
101
  #mentions;
173
- #template;
174
102
  /** @internal Use `session.feed()`. */
175
103
  constructor(session, name, options = {}) {
176
104
  const { path, directory } = feedPaths(name);
@@ -178,15 +106,8 @@ export class PupsFeed {
178
106
  this.path = path;
179
107
  this.directory = directory;
180
108
  this.#session = session;
181
- this.#maxItems = options.maxItems ?? 30;
182
- this.#archiveSize = options.archiveSize ?? 20;
183
- this.#archivesWanted = options.startArchives ?? true;
184
- this.#maxBytes = options.maxBytes;
185
109
  this.#maxAttempts = options.maxAttempts ?? 8;
186
- this.#postUrls = options.postUrls ?? true;
187
110
  this.#mentions = options.mentions === true ? session.mentions : options.mentions || undefined;
188
- if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
189
- throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.');
190
111
  }
191
112
  /** The public URL of the feed file, its `feed_url`. */
192
113
  get url() {
@@ -198,9 +119,9 @@ export class PupsFeed {
198
119
  }
199
120
  /** Whether the session may write the feed file and the feed directory. */
200
121
  get writable() {
201
- return this.#session.canWrite(this.path) && this.#session.canWrite(this.#archivePath(0));
122
+ return this.#session.canWrite(this.path) && this.#session.canWrite(`${this.directory}images/x`);
202
123
  }
203
- /** Reads the feed file and tells whether it exists, and whether PUPS clients may write it. */
124
+ /** Reads the feed file and tells whether it exists, and whether the server keeps it. */
204
125
  async load(options = {}) {
205
126
  try {
206
127
  const loaded = await this.#read(this.path, options.signal);
@@ -215,11 +136,12 @@ export class PupsFeed {
215
136
  }
216
137
  }
217
138
  /**
218
- * Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the fixed fields
219
- * and the `_pups` marker, and registers the feed in `host-meta.json` (unless `register` is false).
139
+ * Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the `_pups` marker,
140
+ * and registers the feed in `host-meta.json` (unless `register` is false). The server sets the fixed fields.
220
141
  * @returns `registered`: false if the feed couldn't be registered; call `register()` again later, or tell the owner
221
142
  * to add the link to `host-meta.json` by hand.
222
- * @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`.
143
+ * @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`; `unsupported` if
144
+ * the server doesn't keep feeds.
223
145
  */
224
146
  async create(setup, options = {}) {
225
147
  const { icon, favicon, title, ...settings } = setup;
@@ -227,6 +149,7 @@ export class PupsFeed {
227
149
  throw new PupsError('invalid_request', 'A feed needs a title.');
228
150
  this.#checkSettings(settings);
229
151
  this.#checkWritable();
152
+ this.#checkKept();
230
153
  const uploaded = [];
231
154
  try {
232
155
  const iconFile = icon && await this.#upload(icon, 'images/icons/icon-', options.signal);
@@ -239,10 +162,7 @@ export class PupsFeed {
239
162
  const doc = {
240
163
  version: JSON_FEED_VERSION,
241
164
  title,
242
- home_page_url: this.#session.me,
243
- feed_url: this.url,
244
165
  ...description === undefined ? {} : { description },
245
- user_comment: mainComment,
246
166
  ...iconFile ? { icon: iconFile.url } : {},
247
167
  ...faviconFile ? { favicon: faviconFile.url } : {},
248
168
  ...rest,
@@ -292,16 +212,13 @@ export class PupsFeed {
292
212
  this.#checkSettings(changes);
293
213
  if (changes.title === null || (changes.title !== undefined && !changes.title.trim()))
294
214
  throw new PupsError('invalid_request', 'A feed needs a title.');
295
- return this.#transaction(async () => {
296
- const main = await this.#readControlled(this.path, options.signal);
297
- const doc = { ...main.doc };
215
+ return this.#change(doc => {
298
216
  for (const [key, value] of Object.entries(changes))
299
217
  if (value === null)
300
218
  delete doc[key];
301
219
  else if (value !== undefined)
302
220
  doc[key] = value;
303
- return this.#writeMain(doc, main.etag, options.signal);
304
- });
221
+ }, options.signal);
305
222
  }
306
223
  /**
307
224
  * Uploads a new icon (512 × 512) to `/feed/images/icons/` (`/feed/<name>/images/icons/` for a named feed) and
@@ -328,10 +245,13 @@ export class PupsFeed {
328
245
  }
329
246
  /**
330
247
  * 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).
248
+ * (RFC-6 "Built-in receiver"). The owner approves them there, and the server publishes them in a comment feed per
249
+ * post, which the post's `_source.comments` names (RFC-7 "Publishing comments"). With `publish: false`, the owner only
250
+ * reads them. Writes RFC-4 `_submissions` into the feed file, with `comment_endpoint` as `url`, the comments policy
251
+ * (RFC-4's defaults for `title`, `minLength` and `maxLength`, and `maxDepth: 1`, since the server accepts comments
252
+ * on posts only, overridden by `policy`) and `republish: "full"`, or `"no"`. Replaces the `_submissions` of another
253
+ * service; check `comments()` first and ask the owner. Single posts are closed with
254
+ * `_commenting: { allowComments: false }` (RFC-4).
335
255
  * @throws {PupsError} `unsupported` if the server has no `comment_endpoint`.
336
256
  */
337
257
  async enableComments(settings = {}, options = {}) {
@@ -342,8 +262,8 @@ export class PupsFeed {
342
262
  about: RFC4_URL,
343
263
  url,
344
264
  ...settings.tos ? { tos: settings.tos } : {},
345
- policies: { comments: { title: 'none', minLength: 2, maxLength: 2000, ...settings.policy } },
346
- republish: 'no',
265
+ policies: { comments: { title: 'none', minLength: 2, maxLength: 2000, maxDepth: 1, ...settings.policy } },
266
+ republish: settings.publish == false ? 'no' : 'full',
347
267
  }, options.signal);
348
268
  }
349
269
  /** Closes the feed for comments: removes `_submissions` from the feed file, whichever service it names. */
@@ -351,11 +271,12 @@ export class PupsFeed {
351
271
  return this.#setSubmissions(undefined, options.signal);
352
272
  }
353
273
  #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
- });
274
+ return this.#change(doc => {
275
+ if (submissions)
276
+ doc._submissions = submissions;
277
+ else
278
+ delete doc._submissions;
279
+ }, signal);
359
280
  }
360
281
  /**
361
282
  * Uploads an image, audio or video file into the feed directory under a new, unique name, by default
@@ -367,98 +288,41 @@ export class PupsFeed {
367
288
  const folder = (options.folder ?? (type.startsWith('image/') ? 'images' : 'media')).replace(/^\/+|\/+$/g, '');
368
289
  if (folder == 'images/icons' || folder.startsWith('images/icons/'))
369
290
  throw new PupsError('invalid_request', `${this.directory}images/icons/ is reserved for the feed's icons (RFC-7, Icons).`);
291
+ if (folder.split('/')[0] == 'comments')
292
+ throw new PupsError('invalid_request', `${this.directory}comments/ is reserved for the comment feeds that the server writes (RFC-7, Publishing comments).`);
370
293
  if (this.name === undefined && !mainMediaFolders.includes(folder.split('/')[0]))
371
294
  throw new PupsError('invalid_request', `The main feed's media go into /feed/images/ or /feed/media/; the rest of /feed/ belongs to named feeds (RFC-7, Items).`);
372
295
  return this.#upload(media, `${folder}/${new Date().getUTCFullYear()}/`, options.signal);
373
296
  }
374
297
  /**
375
- * Adds a post (RFC-7 "Posting with archives"): first to the newest archive, or to a new archive once the newest
376
- * holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
377
- * archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
378
- * media with `uploadMedia()` before posting.
379
- * In a feed with archives, a post without `url` gets one from the site's post URL template, if `host-meta.json`
380
- * has one and `postUrls` isn't false: the page that shows the post (RFC-7 "Post URLs").
298
+ * Adds a post (RFC-7 "Posting items"): sends it to the server, which gives it its index, puts it into the newest
299
+ * archive and at the top of the feed file, and, if the site declares a post URL template, gives it the `url` of
300
+ * its page. Upload media with `uploadMedia()` before posting.
381
301
  * With the option `mentions`, the domains the post names and the author of the item it answers are notified
382
302
  * (RFC-11) once the post is visible; see `PostResult.mentions`.
383
- * @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
384
- * archives, the feed file's URL plus `#<id>`, valid while the post is among the newest. The post's page, if it
385
- * has one, is `item.url`.
303
+ * @returns the post as stored, with `url`: its address, which never changes. The post's page, if it has one, is
304
+ * `item.url`.
305
+ * @throws {PupsError} `not_found` if the feed doesn't exist; `not_pups_controlled`; `unsupported` if the server
306
+ * doesn't keep feeds.
386
307
  */
387
308
  async addPost(input, options = {}) {
388
- const item = this.#newItem(input);
389
- const signal = options.signal;
390
- let archiveUrl = '';
391
- let stored = item;
392
- let firstAttempt = true;
393
- await this.#transaction(async () => {
394
- const main = await this.#readControlled(this.path, signal);
395
- // On a retry, the item may be in the feed file already: another client repaired it from the archive.
396
- if (firstAttempt && main.doc.items.some(i => i.id == item.id))
397
- throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`);
398
- firstAttempt = false;
399
- const doc = { ...main.doc, _archive: { ...main.doc._archive } };
400
- const hasArchives = this.#archiveNumber(doc._archive.archive_url) !== undefined;
401
- if (!hasArchives && !this.#archivesWanted) {
402
- // A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
403
- archiveUrl = this.url;
404
- const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)));
405
- stored = withIndex(item, indexed.next);
406
- doc._archive.next_index = indexed.next + 1;
407
- await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal);
408
- return;
409
- }
410
- if (!hasArchives) {
411
- const started = await this.#startArchives(main, signal);
412
- if (started) {
413
- doc._archive.archive_url = started.url;
414
- doc.items = started.items;
415
- }
416
- }
417
- const template = await this.#postUrlTemplate(signal);
418
- const added = await this.#addToArchive(main, doc, item, signal, template);
419
- archiveUrl = added.url;
420
- stored = added.item;
421
- doc._archive.archive_url = added.url;
422
- if (!hasArchives) {
423
- // The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
424
- // holds the counter.
425
- delete doc.next_url;
426
- delete doc._archive.next_index;
427
- }
428
- doc.items = this.#newestItems(added.recent, doc.items, doc);
429
- await this.#writeMain(doc, main.etag, signal);
430
- });
431
- return this.#withMentions(options.mentions, this.#result(stored, archiveUrl), archiveUrl, stored, undefined, item => !!item);
309
+ const { item, address } = await this.#post(this.#newItem(input), options.signal);
310
+ return this.#withMentions(options.mentions, this.#result(item, address), fileOf(address), item, undefined, found => !!found);
432
311
  }
433
312
  /**
434
- * Gives every item of the feed without an index one (RFC-7 "Indexing an existing feed"), and sets the counter.
435
- * `addPost()` does this by itself before the first post to a feed that hasn't been indexed yet; call it to
436
- * index a feed without posting.
437
- */
438
- async assignIndexes(options = {}) {
439
- const signal = options.signal;
440
- await this.#transaction(async () => {
441
- const main = await this.#readControlled(this.path, signal);
442
- const newest = this.#archiveNumber(main.doc._archive?.archive_url);
443
- if (newest === undefined) {
444
- const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)));
445
- if (indexed.changed || counterOf(main.doc) !== indexed.next)
446
- await this.#writeMain({ ...main.doc, items: indexed.items, _archive: { ...main.doc._archive, next_index: indexed.next } }, main.etag, signal);
447
- return;
448
- }
449
- const archive = await this.#readArchive(this.#archivePath(newest), signal);
450
- if (archive && archive != 'foreign' && (counterOf(archive.doc) === undefined || archive.doc.items.some(item => itemIndex(item) === undefined)))
451
- await this.#indexArchives(main, signal);
452
- });
453
- }
454
- /**
455
- * Finds a post by id in the archives (or, for a handed-over feed without archives yet, in the feed file).
313
+ * Finds a post by id in the archives.
456
314
  * @returns undefined if there is no such post.
457
315
  */
458
316
  async getPost(id, options = {}) {
459
317
  const main = await this.#read(this.path, options.signal);
460
- const found = main && await this.#find(main, id, options.signal);
461
- return found && this.#result(found.file.doc.items[found.index], this.#session.publicUrl(found.file.path));
318
+ if (!main)
319
+ return;
320
+ for await (const file of this.#chain(main, options.signal)) {
321
+ const item = file.doc.items.find(i => i.id == id);
322
+ if (item)
323
+ return this.#result(item, `${this.#session.publicUrl(file.path)}#${encodeURIComponent(id)}`);
324
+ }
325
+ return;
462
326
  }
463
327
  /**
464
328
  * All posts, newest first: the archives from `_archive.archive_url` along `next_url` (for a feed without archives,
@@ -477,75 +341,39 @@ export class PupsFeed {
477
341
  }
478
342
  }
479
343
  /**
480
- * Edits a post in its archive, and in the feed file if it is among the newest items (RFC-7 "Editing and deleting
481
- * items"), and sets `date_modified`. `changes` is either an object (a value sets a field, `null` removes it), or
482
- * a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
483
- * function may run more than once.
344
+ * Edits a post (RFC-7 "Posting items"): reads it from its archive, applies `changes`, and sends it to the server,
345
+ * which replaces it in its archive and in the feed file and sets `date_modified`. `changes` is either an object (a
346
+ * value sets a field, `null` removes it), or a function that gets a copy of the item and returns the new item, or
347
+ * `undefined` to leave it unchanged. The post keeps its id and index.
484
348
  *
485
349
  * 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
487
- * archives that has no `url`, and had none before, gets one from the post URL template, as in `addPost()`.
350
+ * `mentions`, everyone the old or the new version mentions is notified.
488
351
  * @throws {PupsError} `not_found`
489
352
  */
490
353
  async editPost(id, changes, options = {}) {
491
354
  const signal = options.signal;
492
- let edit;
493
- const result = await this.#transaction(async () => {
494
- edit = undefined;
495
- const { main, file, index } = await this.#findWritable(id, signal);
496
- const old = file.doc.items[index];
497
- const fileUrl = this.#session.publicUrl(file.path);
498
- const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes);
499
- if (!changed)
500
- return this.#result(old, fileUrl);
501
- const oldIndex = itemIndex(old);
502
- let item = { ...changed, id, date_modified: now() };
503
- // The index never changes (RFC-7 "Indexes").
504
- if (oldIndex !== undefined)
505
- item = withIndex(item, oldIndex);
506
- // A post of a feed with archives that never had a url may get one (RFC-7 "Post URLs").
507
- if (oldIndex !== undefined && !old.url && !item.url && this.#archiveNumber(main.doc._archive?.archive_url) !== undefined)
508
- item = this.#withPostUrl(item, oldIndex, await this.#postUrlTemplate(signal));
509
- if (file != main)
510
- await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal);
511
- const mainIndex = main.doc.items.findIndex(i => i.id == id);
512
- if (mainIndex >= 0)
513
- await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal);
514
- edit = { old, item, fileUrl };
515
- return this.#result(item, fileUrl);
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;
355
+ const current = await this.getPost(id, options);
356
+ if (!current)
357
+ throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`);
358
+ const old = current.item;
359
+ const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes);
360
+ if (!changed)
361
+ return current;
362
+ // The index names the post for the server (RFC-7 "Posting items"), and never changes.
363
+ const { _pups: _marker, ...rest } = changed;
364
+ const { item, address } = await this.#post({ ...rest, id, _archive: { ...isObject(rest._archive) ? rest._archive : {}, ...old._archive } }, signal);
365
+ return this.#withMentions(options.mentions, this.#result(item, address), fileOf(address), item, old, found => found?.date_modified == item.date_modified);
519
366
  }
520
367
  /**
521
- * Deletes a post from its archive and from the feed file, which is then filled up again with the newest items
522
- * from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the post references
523
- * and no other post does; this reads all archives.
368
+ * Deletes a post (RFC-7 "Posting items"): the server removes it from its archive and from the feed file, which it
369
+ * fills up again from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the
370
+ * post references and no other post does; this reads all archives.
524
371
  * @returns the deleted item, and the public URLs of the deleted media files.
525
372
  * @throws {PupsError} `not_found`
526
373
  */
527
374
  async deletePost(id, options = {}) {
528
375
  const signal = options.signal;
529
- let fileUrl = '';
530
- const item = await this.#transaction(async () => {
531
- const { main, file, index } = await this.#findWritable(id, signal);
532
- fileUrl = this.#session.publicUrl(file.path);
533
- const item = file.doc.items[index];
534
- if (file != main) {
535
- await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal);
536
- // Fill the feed file up again from the archives, which no longer contain the item.
537
- const newest = [];
538
- for await (const archive of this.#chain(main, signal)) {
539
- newest.push(...archive.doc.items.filter(i => i.id != id));
540
- if (newest.length >= this.#maxItems)
541
- break;
542
- }
543
- await this.#writeMain({ ...main.doc, items: this.#newestItems(newest, [], main.doc) }, main.etag, signal);
544
- }
545
- else
546
- await this.#writeMain({ ...main.doc, items: main.doc.items.filter(i => i.id != id) }, main.etag, signal);
547
- return item;
548
- });
376
+ const { item, address } = await this.#post({ id, _pups: { delete: true } }, signal);
549
377
  const deletedMedia = [];
550
378
  if (options.deleteMedia) {
551
379
  const candidates = new Set(this.#mediaUrls(item));
@@ -559,7 +387,7 @@ export class PupsFeed {
559
387
  deletedMedia.push(url);
560
388
  }
561
389
  }
562
- const mentions = this.#sendMentions(options.mentions, fileUrl, undefined, item, found => !found);
390
+ const mentions = this.#sendMentions(options.mentions, fileOf(address), undefined, item, found => !found);
563
391
  return { item, deletedMedia, ...mentions ? { mentions } : {} };
564
392
  }
565
393
  /**
@@ -575,9 +403,9 @@ export class PupsFeed {
575
403
  }
576
404
  /**
577
405
  * 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.
406
+ * (RFC-4 "Submitting"): `source` is the post's address, `target` its `_source.inReplyTo`. Call it after `addPost()`
407
+ * or `editPost()`, also to submit an edit or a delete again. Show the target's terms of service and what its
408
+ * `republish` means before the first submission.
581
409
  * @throws {PupsError} `not_found`; `invalid_request` if the post answers nothing; `unsupported` if the target
582
410
  * feed takes no submissions.
583
411
  * @deprecated Comments and group posts don't belong in a feed for readers (RFC-7 "Comment feeds"). Use
@@ -652,21 +480,12 @@ export class PupsFeed {
652
480
  }
653
481
  if (!isFeedDocument(doc))
654
482
  throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`);
655
- return { path, doc: upgradeArchiveFields(doc), etag: file.etag };
656
- }
657
- /** Reads a file that must exist and carry the `_pups` marker. */
658
- async #readControlled(path, signal) {
659
- const loaded = await this.#read(path, signal);
660
- if (!loaded)
661
- throw new PupsError('not_found', path == this.path ? `There is no feed at ${path} yet. Set it up with create().` : `${path} doesn't exist.`);
662
- if (!isControlled(loaded.doc))
663
- throw notControlled(path);
664
- return loaded;
483
+ return { path, doc, etag: file.etag };
665
484
  }
666
485
  /**
667
486
  * The files that hold all items: the archives from `_archive.archive_url` along `next_url`, as far as they are files
668
- * on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
669
- * the pages its `next_url` names.
487
+ * on this server. A feed without archives (handed over, not written yet) holds its items in the feed file and the
488
+ * pages its `next_url` names.
670
489
  */
671
490
  async *#chain(main, signal) {
672
491
  const visited = new Set([main.path]);
@@ -697,308 +516,54 @@ export class PupsFeed {
697
516
  yield file;
698
517
  }
699
518
  }
700
- async #find(main, id, signal) {
701
- for await (const file of this.#chain(main, signal)) {
702
- const index = file.doc.items.findIndex(item => item.id == id);
703
- if (index >= 0)
704
- return { main, file, index };
705
- }
706
- return;
707
- }
708
- async #findWritable(id, signal) {
709
- const main = await this.#readControlled(this.path, signal);
710
- const found = await this.#find(main, id, signal);
711
- if (!found)
712
- throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`);
713
- if (!isControlled(found.file.doc))
714
- throw notControlled(found.file.path);
715
- return found;
716
- }
717
519
  // Writing
718
- /** Runs `operation` again when another client changed a file in between, up to `maxAttempts` times. */
719
- async #transaction(operation) {
720
- for (let attempt = 1;; attempt++)
721
- try {
722
- return await operation();
723
- }
724
- catch (e) {
725
- if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts)
726
- throw e;
727
- }
728
- }
729
- /**
730
- * Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
731
- * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). A feed with archives gets the archive template
732
- * and size of RFC-13, and its optional `next_url` is kept equal to `archive_url` (RFC-7 "Reading").
733
- */
734
- async #writeMain(doc, etag, signal) {
735
- const { author, ...rest } = doc;
736
- const fixed = {
737
- ...rest,
738
- version: JSON_FEED_VERSION,
739
- home_page_url: this.#session.me,
740
- feed_url: this.url,
741
- user_comment: mainComment,
742
- };
743
- if (author !== undefined && fixed.authors === undefined)
744
- fixed.authors = [author];
745
- const archiveUrl = fixed._archive?.archive_url;
746
- if (fixed._archive)
747
- fixed._archive = { about: ARCHIVE_SPEC, ...fixed._archive };
748
- if (this.#archiveNumber(archiveUrl) !== undefined) {
749
- fixed._archive = { ...fixed._archive, archive_template: this.#archiveTemplate(), archive_size: this.#archiveSize };
750
- if (fixed.next_url !== undefined)
751
- fixed.next_url = archiveUrl;
752
- }
753
- await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal });
754
- return fixed;
755
- }
756
- /**
757
- * Writes an archive with `items`, and with the counter `next_index` if given. An archive of an earlier draft gets its
758
- * `_archive` fields and comment of RFC-13 (`number`, `updates_url`).
759
- */
760
- async #writeArchive(archive, items, signal, nextIndex) {
761
- const n = this.#archiveNumber(this.#session.publicUrl(archive.path));
762
- const fields = { about: ARCHIVE_SPEC, ...archive.doc._archive, updates_url: this.url, ...n === undefined ? {} : { number: n } };
763
- if (nextIndex !== undefined)
764
- fields.next_index = nextIndex;
765
- const doc = { ...archive.doc, user_comment: archiveComment(this.url), items, _archive: fields };
766
- await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal });
767
- }
768
- /**
769
- * The items of the feed file: the newest archive items first (which also repairs items an interrupted post wrote
770
- * only into the archive), then the other items of the feed file, at most `maxItems`, fewer if `maxBytes` is set
771
- * and exceeded, but at least 10.
772
- */
773
- #newestItems(recent, current, doc) {
774
- const ids = new Set(recent.map(item => item.id));
775
- const items = [...recent, ...current.filter(item => !ids.has(item.id))].slice(0, this.#maxItems);
776
- if (this.#maxBytes)
777
- while (items.length > minFeedItems && byteLength(serialize({ ...doc, items })) > this.#maxBytes)
778
- items.pop();
779
- return items;
780
- }
781
- // Archives
782
- #archivePath(n) {
783
- return `${this.directory}feed.${String(n).padStart(6, '0')}.json`;
784
- }
785
- #archiveUrl(n) {
786
- return this.#session.publicUrl(this.#archivePath(n));
787
- }
788
- /** `_archive.archive_template` (RFC-13): the archive URL with `{number}` for the number. */
789
- #archiveTemplate() {
790
- return this.#archiveUrl(0).replace(/000000\.json$/, '{number}.json');
791
- }
792
- /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
793
- #archiveNumber(url) {
794
- const path = url && pathFromPublicUrl(this.#session.server, url);
795
- if (!path?.startsWith(this.directory))
796
- return;
797
- const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length));
798
- return match ? Number(match[1]) : undefined;
799
- }
800
- /**
801
- * A new archive with the feed fields of the feed file (RFC-13 "Feed fields of an archive"), except `_submissions`:
802
- * whether a feed accepts comments is said by its feed file alone.
803
- */
804
- #newArchive(n, main, items, nextUrl, nextIndex) {
805
- const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, _archive, _submissions: _s, ...fields } = main;
806
- const podcast = fields._podcast;
807
- if (isObject(podcast) && 'liveItems' in podcast) {
808
- const { liveItems: _live, ...rest } = podcast;
809
- fields._podcast = rest;
810
- }
811
- return {
812
- ...fields,
813
- version: JSON_FEED_VERSION,
814
- home_page_url: this.#session.me,
815
- feed_url: this.#archiveUrl(n),
816
- user_comment: archiveComment(this.url),
817
- ...nextUrl ? { next_url: nextUrl } : {},
818
- items,
819
- _pups: { about: PUPS_FEED_SPEC, ..._pups, pupsControlled: true },
820
- _archive: { about: ARCHIVE_SPEC, updates_url: this.url, number: n, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
821
- };
822
- }
823
- async #createArchive(n, main, items, nextUrl, signal, nextIndex) {
824
- await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl, nextIndex)), { contentType: FEED_CONTENT_TYPE, signal });
825
- }
826
- /**
827
- * Reads an archive for writing.
828
- * @returns undefined if it doesn't exist, 'foreign' if it exists but is no PUPS archive.
829
- */
830
- async #readArchive(path, signal) {
520
+ /** Sends an item to the server (RFC-7 "Posting items"). */
521
+ async #post(item, signal) {
522
+ this.#checkKept();
831
523
  try {
832
- const loaded = await this.#read(path, signal);
833
- return loaded && !isControlled(loaded.doc) ? 'foreign' : loaded;
524
+ return posted((await this.#session.post(this.path, item, { signal })).body, this.path);
834
525
  }
835
526
  catch (e) {
836
- if (isPupsError(e, 'invalid_feed'))
837
- return 'foreign';
527
+ if (isPupsError(e, 'not_pups_controlled'))
528
+ throw notControlled(this.path);
529
+ if (isPupsError(e, 'not_found') && !await this.#session.get(this.path, { signal }))
530
+ throw new PupsError('not_found', `There is no feed at ${this.path} yet. Set it up with create().`, { cause: e });
838
531
  throw e;
839
532
  }
840
533
  }
841
534
  /**
842
- * Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
843
- * archives"). The items get indexes first, and the newest archive the counter. The oldest archive continues the
844
- * feed's `next_url` chain.
845
- * @returns the URL of the newest archive and the feed's items with their indexes, or undefined if the feed has no
846
- * items.
535
+ * Changes the feed file's fields with `change` and writes it with `If-Match`; reads it again and repeats when
536
+ * someone else wrote in between, up to `maxAttempts` times. The server keeps the items and the archive fields.
537
+ * @returns the feed as written.
847
538
  */
848
- async #startArchives(main, signal) {
849
- const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)));
850
- const oldestFirst = [...indexed.items].reverse();
851
- const count = Math.ceil(oldestFirst.length / this.#archiveSize);
852
- let url;
853
- for (let n = 0; n < count; n++) {
854
- const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse();
855
- const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url;
856
- const nextIndex = n == count - 1 ? indexed.next : undefined;
539
+ async #change(change, signal) {
540
+ for (let attempt = 1;; attempt++) {
541
+ const main = await this.#read(this.path, signal);
542
+ if (!main)
543
+ throw new PupsError('not_found', `There is no feed at ${this.path} yet. Set it up with create().`);
544
+ if (!isControlled(main.doc))
545
+ throw notControlled(this.path);
546
+ const doc = clone(main.doc);
547
+ change(doc);
857
548
  try {
858
- await this.#createArchive(n, main.doc, items, nextUrl, signal, nextIndex);
549
+ await this.#session.replace(this.path, serialize(doc), main.etag, { contentType: FEED_CONTENT_TYPE, signal });
550
+ return doc;
859
551
  }
860
552
  catch (e) {
861
- if (!isPupsError(e, 'precondition_failed'))
553
+ if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts)
862
554
  throw e;
863
- // Left behind by an interrupted start: complete it, as long as it holds only these items.
864
- const existing = await this.#readArchive(this.#archivePath(n), signal);
865
- const ids = new Set(items.map(item => item.id));
866
- if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
867
- 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).`);
868
- await this.#writeArchive(existing, items, signal, nextIndex);
869
555
  }
870
- url = this.#archiveUrl(n);
871
556
  }
872
- return url ? { url, items: indexed.items } : undefined;
873
557
  }
874
- /**
875
- * Indexes a feed with archives whose newest archive has no counter, or items without an index (RFC-7 "Indexing an
876
- * existing feed"): gives every archived item without an index one, the oldest first, writes the changed archives
877
- * from the oldest to the newest, the newest with the counter, and then the feed file's copies.
878
- */
879
- async #indexArchives(main, signal) {
880
- const files = [];
881
- for await (const file of this.#chain(main, signal)) {
882
- // Pages behind the oldest archive of a handed-over feed are never written, and keep their items unindexed.
883
- if (file == main || !isControlled(file.doc))
884
- break;
885
- files.push(file);
886
- }
887
- if (!files.length)
558
+ /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
559
+ #archiveNumber(url) {
560
+ const path = url && pathFromPublicUrl(this.#session.server, url);
561
+ if (!path?.startsWith(this.directory))
888
562
  return;
889
- let next = nextFree(files.flatMap(file => file.doc.items), ...files.map(file => counterOf(file.doc)));
890
- const indexes = new Map();
891
- for (const file of [...files].reverse()) {
892
- const indexed = indexItems(file.doc.items, next);
893
- next = indexed.next;
894
- for (const item of indexed.items)
895
- indexes.set(item.id, itemIndex(item));
896
- const newest = file == files[0];
897
- if (indexed.changed || (newest && counterOf(file.doc) !== next))
898
- await this.#writeArchive(file, indexed.items, signal, newest ? next : undefined);
899
- }
900
- let changed = false;
901
- const items = main.doc.items.map(item => {
902
- const index = indexes.get(item.id);
903
- if (index === undefined || itemIndex(item) === index)
904
- return item;
905
- changed = true;
906
- return withIndex(item, index);
907
- });
908
- if (changed)
909
- await this.#writeMain({ ...main.doc, items }, main.etag, signal);
910
- }
911
- /**
912
- * Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
913
- * "Posting"). Writes only archives; the caller writes the feed file afterwards.
914
- * The item gets its index from the archive's counter (RFC-7 "Indexes"); a newest archive without a counter is
915
- * indexed first, and the post then starts again.
916
- * @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
917
- */
918
- async #addToArchive(main, doc, item, signal, template) {
919
- const place = (index) => this.#withPostUrl(withIndex(item, index), index, template);
920
- const newest = this.#archiveNumber(doc._archive?.archive_url);
921
- let previous = [];
922
- // The index for the item if it goes into a new archive.
923
- let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined);
924
- if (newest !== undefined) {
925
- const existing = await this.#readArchive(this.#archivePath(newest), signal);
926
- if (!existing) {
927
- // The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
928
- const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined;
929
- if (before && before != 'foreign')
930
- next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc));
931
- const stored = place(next);
932
- await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1);
933
- return { url: this.#archiveUrl(newest), recent: [stored], item: stored };
934
- }
935
- if (existing != 'foreign') {
936
- if (counterOf(existing.doc) === undefined) {
937
- await this.#indexArchives(main, signal);
938
- throw conflict(`${this.path} was indexed, so it`);
939
- }
940
- // Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
941
- const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)));
942
- const copy = indexed.items.find(i => i.id == item.id);
943
- const stored = place(copy ? itemIndex(copy) : indexed.next);
944
- const merged = mergeItems(indexed.items, [stored]);
945
- if (merged.length <= this.#archiveSize) {
946
- await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1);
947
- return { url: this.#archiveUrl(newest), recent: merged, item: stored };
948
- }
949
- if (indexed.changed)
950
- await this.#writeArchive(existing, indexed.items, signal, indexed.next);
951
- previous = indexed.items;
952
- next = indexed.next;
953
- }
954
- }
955
- // The archive before the new one: the newest, or for a feed without archives the end of its old chain.
956
- const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest);
957
- for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
958
- const stored = place(next);
959
- try {
960
- await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1);
961
- return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored };
962
- }
963
- catch (e) {
964
- if (!isPupsError(e, 'precondition_failed'))
965
- throw e;
966
- }
967
- // The archive exists: left behind by an interrupted client, or created by another client just now.
968
- const existing = await this.#readArchive(this.#archivePath(n), signal);
969
- if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
970
- const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next));
971
- const copy = indexed.items.find(i => i.id == item.id);
972
- const added = place(copy ? itemIndex(copy) : indexed.next);
973
- const merged = mergeItems(indexed.items, [added]);
974
- if (merged.length <= this.#archiveSize) {
975
- await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1);
976
- return { url: this.#archiveUrl(n), recent: [...merged, ...previous], item: added };
977
- }
978
- }
979
- const current = await this.#session.get(this.path, { signal });
980
- if (current?.etag != main.etag)
981
- throw conflict(this.path);
982
- }
983
- throw new PupsError('conflict', `No free archive number in ${this.directory}.`);
563
+ const match = /^feed\.(\d{6,})\.json$/.exec(path.slice(this.directory.length));
564
+ return match ? Number(match[1]) : undefined;
984
565
  }
985
566
  // Items and media
986
- /** The site's post URL template from `host-meta.json`, read once; undefined if there is none or it can't be read. */
987
- #postUrlTemplate(signal) {
988
- if (!this.#postUrls)
989
- return Promise.resolve(undefined);
990
- this.#template ??= this.#session.hostMeta.get({ signal })
991
- .then(doc => doc.properties?.[POST_URL_TEMPLATE])
992
- .then(template => validTemplate(template) ? template : undefined, () => undefined);
993
- return this.#template;
994
- }
995
- /** The item with the `url` from the post URL template (RFC-7 "Post URLs"), unless it has one. */
996
- #withPostUrl(item, index, template) {
997
- if (!template || item.url)
998
- return item;
999
- const vars = { feed: this.path.slice(1, -'.json'.length), index: String(index), id: encodeURIComponent(item.id) };
1000
- return { ...item, url: template.replace(/\{(feed|index|id)\}/g, (_, name) => vars[name]) };
1001
- }
1002
567
  #newItem(input) {
1003
568
  const { id, markdown, date_published, ...fields } = input;
1004
569
  if (id !== undefined && (typeof id != 'string' || !id))
@@ -1012,16 +577,14 @@ export class PupsFeed {
1012
577
  this.#setMarkdown(item, markdown);
1013
578
  if (item.content_html === undefined && item.content_text === undefined)
1014
579
  throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).');
1015
- // The index is given out when the item is added (RFC-13 "Indexes").
1016
- for (const key of ['_archive', '_pups']) {
1017
- const value = item[key];
1018
- if (!isObject(value))
1019
- continue;
1020
- const { index: _index, ...rest } = value;
580
+ // An item with an index names an existing item; the server gives new items theirs (RFC-7 "Posting items").
581
+ delete item._pups;
582
+ if (isObject(item._archive)) {
583
+ const { index: _index, ...rest } = item._archive;
1021
584
  if (Object.keys(rest).length)
1022
- item[key] = rest;
585
+ item._archive = rest;
1023
586
  else
1024
- delete item[key];
587
+ delete item._archive;
1025
588
  }
1026
589
  return item;
1027
590
  }
@@ -1058,9 +621,9 @@ export class PupsFeed {
1058
621
  if (item.content_html === undefined)
1059
622
  item.content_text = markdown;
1060
623
  }
1061
- #result(item, fileUrl) {
624
+ #result(item, address) {
1062
625
  const index = itemIndex(item);
1063
- return { id: item.id, ...index === undefined ? {} : { index }, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` };
626
+ return { id: item.id, ...index === undefined ? {} : { index }, item, url: address };
1064
627
  }
1065
628
  /**
1066
629
  * The URLs of this feed's media files (not icons, not archives) that an item references. For the main feed, only
@@ -1101,16 +664,13 @@ export class PupsFeed {
1101
664
  let old;
1102
665
  let doc;
1103
666
  try {
1104
- doc = await this.#transaction(async () => {
1105
- const main = await this.#readControlled(this.path, signal);
1106
- old = main.doc[field];
1107
- const changed = { ...main.doc };
667
+ doc = await this.#change(doc => {
668
+ old = doc[field];
1108
669
  if (uploaded)
1109
- changed[field] = uploaded.url;
670
+ doc[field] = uploaded.url;
1110
671
  else
1111
- delete changed[field];
1112
- return this.#writeMain(changed, main.etag, signal);
1113
- });
672
+ delete doc[field];
673
+ }, signal);
1114
674
  }
1115
675
  catch (e) {
1116
676
  if (uploaded)
@@ -1143,6 +703,10 @@ export class PupsFeed {
1143
703
  else if (!['title', 'description', 'authors', 'language', 'expired'].includes(key) && !key.startsWith('_'))
1144
704
  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 "_".`);
1145
705
  }
706
+ #checkKept() {
707
+ if (!this.#session.server.keptFeeds)
708
+ throw new PupsError('unsupported', `This PUPS server doesn't keep feeds: its configuration has no "kept_feeds": true (RFC-7, Server requirements).`);
709
+ }
1146
710
  #checkWritable() {
1147
711
  if (!this.writable)
1148
712
  throw new PupsError('insufficient_scope', `Writing ${this.path} needs the scopes ${this.scopes.join(' ')} (RFC-7, Server requirements).`);