pups-client 0.1.0 → 0.3.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.
Files changed (47) hide show
  1. package/README.md +61 -4
  2. package/dist/cli/main.js +4 -4
  3. package/dist/cli/main.js.map +1 -1
  4. package/dist/discovery.d.ts +2 -0
  5. package/dist/discovery.d.ts.map +1 -1
  6. package/dist/discovery.js +1 -0
  7. package/dist/discovery.js.map +1 -1
  8. package/dist/errors.d.ts +4 -0
  9. package/dist/errors.d.ts.map +1 -1
  10. package/dist/errors.js.map +1 -1
  11. package/dist/feed.d.ts +337 -0
  12. package/dist/feed.d.ts.map +1 -0
  13. package/dist/feed.js +945 -0
  14. package/dist/feed.js.map +1 -0
  15. package/dist/host-meta.d.ts +22 -3
  16. package/dist/host-meta.d.ts.map +1 -1
  17. package/dist/host-meta.js +37 -5
  18. package/dist/host-meta.js.map +1 -1
  19. package/dist/index.d.ts +2 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/paths.d.ts +11 -1
  24. package/dist/paths.d.ts.map +1 -1
  25. package/dist/paths.js +17 -1
  26. package/dist/paths.js.map +1 -1
  27. package/dist/scopes.d.ts +15 -4
  28. package/dist/scopes.d.ts.map +1 -1
  29. package/dist/scopes.js +21 -9
  30. package/dist/scopes.js.map +1 -1
  31. package/dist/session.d.ts +50 -7
  32. package/dist/session.d.ts.map +1 -1
  33. package/dist/session.js +81 -15
  34. package/dist/session.js.map +1 -1
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/package.json +1 -1
  38. package/src/cli/main.ts +4 -4
  39. package/src/discovery.ts +3 -0
  40. package/src/errors.ts +5 -0
  41. package/src/feed.ts +1162 -0
  42. package/src/host-meta.ts +43 -7
  43. package/src/index.ts +20 -0
  44. package/src/paths.ts +19 -1
  45. package/src/scopes.ts +33 -11
  46. package/src/session.ts +90 -18
  47. package/src/version.ts +1 -1
package/src/feed.ts ADDED
@@ -0,0 +1,1162 @@
1
+ import { isPupsError, PupsError } from './errors.js'
2
+ import { fileTypes } from './file-types.js'
3
+ import { pathFromPublicUrl } from './paths.js'
4
+ import type { Scope } from './scopes.js'
5
+ import type { Body, PupsSession } from './session.js'
6
+ import { randomString } from './util.js'
7
+
8
+ /** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
9
+ export const FEED_REL = 'https://bigwide.net/ns/feed'
10
+
11
+ /** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
12
+ export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md'
13
+
14
+ const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md'
15
+ const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1'
16
+ const FEED_CONTENT_TYPE = 'application/feed+json'
17
+ const maxArchiveNumber = 999_999
18
+ /** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
19
+ const minFeedItems = 10
20
+
21
+ 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.`
22
+ const archiveComment = (feedUrl: string) =>
23
+ `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
+
25
+ /** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
26
+ const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
27
+
28
+ /** The main feed's media directories in `/feed/`, which therefore can't be feed names. */
29
+ const mainMediaFolders = ['images', 'media']
30
+
31
+ /** Top-level fields that are fixed or managed by RFC-7, and can't be set through `create()` or `updateSettings()`. */
32
+ const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', 'icon', 'favicon'])
33
+
34
+ export interface FeedAuthor {
35
+ name?: string
36
+ url?: string
37
+ avatar?: string
38
+ [field: string]: unknown
39
+ }
40
+
41
+ export interface FeedAttachment {
42
+ url: string
43
+ mime_type: string
44
+ title?: string
45
+ size_in_bytes?: number
46
+ duration_in_seconds?: number
47
+ [field: string]: unknown
48
+ }
49
+
50
+ /** A JSON Feed 1.1 item. */
51
+ export interface FeedItem {
52
+ id: string
53
+ url?: string
54
+ external_url?: string
55
+ title?: string
56
+ content_html?: string
57
+ content_text?: string
58
+ summary?: string
59
+ image?: string
60
+ banner_image?: string
61
+ date_published?: string
62
+ date_modified?: string
63
+ authors?: FeedAuthor[]
64
+ tags?: string[]
65
+ language?: string
66
+ attachments?: FeedAttachment[]
67
+ /** The item's `_pups` object, with its index (RFC-7 "Indexes"). */
68
+ _pups?: ItemMarker
69
+ [field: string]: unknown
70
+ }
71
+
72
+ /** The `_pups` object of an item. */
73
+ export interface ItemMarker {
74
+ /** The item's index: 0 for a feed's first item, then counting up; never changed, never used again (RFC-7 "Indexes"). */
75
+ index?: number
76
+ [field: string]: unknown
77
+ }
78
+
79
+ /** The `_pups` object of a feed file or archive. */
80
+ export interface PupsMarker {
81
+ about?: string
82
+ pupsControlled?: boolean
83
+ /** In the feed file: the public URL of the newest archive. */
84
+ archive_url?: string
85
+ /** In an archive: the public URL of the feed file, which readers poll. */
86
+ updates_url?: string
87
+ /**
88
+ * The index the next new item gets (RFC-7 "Indexes"). Valid in the newest archive, or in the feed file of a feed
89
+ * without archives.
90
+ */
91
+ next_index?: number
92
+ [field: string]: unknown
93
+ }
94
+
95
+ /** A JSON Feed 1.1 document, as stored in a feed file or archive. */
96
+ export interface FeedDocument {
97
+ version: string
98
+ title: string
99
+ home_page_url?: string
100
+ feed_url?: string
101
+ description?: string
102
+ user_comment?: string
103
+ next_url?: string
104
+ icon?: string
105
+ favicon?: string
106
+ authors?: FeedAuthor[]
107
+ language?: string
108
+ expired?: boolean
109
+ hubs?: unknown[]
110
+ items: FeedItem[]
111
+ _pups?: PupsMarker
112
+ [field: string]: unknown
113
+ }
114
+
115
+ /**
116
+ * The fields of a feed that belong to the owner (RFC-7 "Fields"). Extensions such as `_podcast` (RFC-3) or
117
+ * `_source` (RFC-1) are allowed too. Icons are set with `setIcon()` and `setFavicon()`.
118
+ */
119
+ export interface FeedSettings {
120
+ title?: string
121
+ description?: string
122
+ authors?: FeedAuthor[]
123
+ language?: string
124
+ expired?: boolean
125
+ [extension: `_${string}`]: unknown
126
+ }
127
+
128
+ /** Changes to the settings: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
129
+ export type FeedSettingsChanges = { [K in keyof FeedSettings]?: FeedSettings[K] | null }
130
+
131
+ /**
132
+ * An image, audio or video file to upload: a `Blob` (or `File`) with a type or name, or a body with its type or
133
+ * extension. The extension must be on the RFC-6 allowlist.
134
+ */
135
+ export type MediaInput = Blob | { body: Body; type?: string; extension?: string }
136
+
137
+ /** The settings of a new feed. */
138
+ export interface FeedSetup extends FeedSettings {
139
+ title: string
140
+ /** 512 × 512 pixels, stored in `images/icons/` in the feed directory. */
141
+ icon?: MediaInput
142
+ /** 64 × 64 pixels, stored in `images/icons/` in the feed directory. */
143
+ favicon?: MediaInput
144
+ }
145
+
146
+ /** A new post: a JSON Feed item without `id` (generated unless given) and with a few conveniences. */
147
+ export interface PostInput {
148
+ /** Generated if missing: 16 random URL-safe characters. Must be unique across the feed and its archives. */
149
+ id?: string
150
+ title?: string
151
+ content_html?: string
152
+ content_text?: string
153
+ /**
154
+ * The text as Markdown, stored in `_source.markdown` (RFC-1). If neither `content_html` nor `content_text` is
155
+ * given, the Markdown is also used as `content_text`, since JSON Feed requires one of them.
156
+ */
157
+ markdown?: string
158
+ summary?: string
159
+ url?: string
160
+ external_url?: string
161
+ image?: string
162
+ banner_image?: string
163
+ /** Default: now. */
164
+ date_published?: string | Date
165
+ authors?: FeedAuthor[]
166
+ tags?: string[]
167
+ language?: string
168
+ attachments?: FeedAttachment[]
169
+ [extension: `_${string}`]: unknown
170
+ }
171
+
172
+ /** Changes to a post: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
173
+ export type PostChanges = { [K in Exclude<keyof PostInput, 'id'>]?: PostInput[K] | null }
174
+
175
+ export interface PostResult {
176
+ id: string
177
+ /** The item's index (RFC-7 "Indexes"); undefined for an item that has none yet. */
178
+ index?: number
179
+ /** The item as stored. */
180
+ item: FeedItem
181
+ /**
182
+ * The URL of the item's archive plus `#<id>`. Items never leave their archive, so it never changes; use it e.g.
183
+ * as the `source` of an RFC-4 webmention. In a feed without archives, the feed file's URL plus `#<id>`.
184
+ */
185
+ url: string
186
+ }
187
+
188
+ export interface MediaResult {
189
+ path: string
190
+ /** The public URL, to reference from items. */
191
+ url: string
192
+ /** The served type, e.g. for `attachments[].mime_type`. */
193
+ type: string
194
+ size: number
195
+ }
196
+
197
+ export type FeedState =
198
+ /** There is no feed file yet. `create()` sets it up. */
199
+ | { status: 'missing' }
200
+ /** A feed maintained by PUPS clients, ready to write. */
201
+ | { status: 'pups'; feed: FeedDocument; etag: string }
202
+ /** A JSON Feed without `_pups.pupsControlled`: maintained by other means, and never written (RFC-7). */
203
+ | { status: 'foreign'; feed: FeedDocument }
204
+ /** The file exists but is not a JSON Feed. */
205
+ | { status: 'invalid' }
206
+
207
+ export interface FeedOptions {
208
+ /** How many of the newest items the feed file holds. Default 30 (RFC-7 "Feed size"). */
209
+ maxItems?: number
210
+ /** How many items an archive holds. Default 20 (RFC-7 "Archives"); other clients expect 20. */
211
+ archiveSize?: number
212
+ /**
213
+ * Whether to start archives for a feed that has none, on its next post (RFC-7 "Starting the archives").
214
+ * Default true. With false, posts to such a feed only go into the feed file, and items beyond `maxItems` are
215
+ * dropped. Feeds that have archives always keep them.
216
+ */
217
+ startArchives?: boolean
218
+ /**
219
+ * Optional: keep fewer items in the feed file when it would be larger than this many bytes, but at least 10
220
+ * (RFC-7 "Size in bytes").
221
+ */
222
+ maxBytes?: number
223
+ /** How often an operation is repeated when another client changed the feed in between. Default 8. */
224
+ maxAttempts?: number
225
+ }
226
+
227
+ /** A feed registered in `host-meta.json`. */
228
+ export interface FeedLink {
229
+ /** The public URL of the feed file. */
230
+ url: string
231
+ type?: string
232
+ /** Set if the feed is a main or named feed on this PUPS server, in the layout of RFC-7. */
233
+ feed?: PupsFeed
234
+ }
235
+
236
+ type Signal = { signal?: AbortSignal }
237
+
238
+ interface Loaded {
239
+ path: string
240
+ doc: FeedDocument
241
+ etag: string
242
+ }
243
+
244
+ interface Found {
245
+ main: Loaded
246
+ file: Loaded
247
+ index: number
248
+ }
249
+
250
+ /** The scopes an app needs to write a feed: the feed file and the feed directory (RFC-7 "Server requirements"). */
251
+ export function feedScopes(name?: string): Scope[] {
252
+ const { path, directory } = feedPaths(name)
253
+ return [`write:${path}`, `write:${directory}`]
254
+ }
255
+
256
+ function feedPaths(name?: string): { path: `/${string}`; directory: `/${string}` } {
257
+ if (name === undefined) return { path: '/feed.json', directory: '/feed/' }
258
+ if (!feedNamePattern.test(name))
259
+ 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).`)
260
+ if (mainMediaFolders.includes(name))
261
+ 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).`)
262
+ return { path: `/feed/${name}.json`, directory: `/feed/${name}/` }
263
+ }
264
+
265
+ const isObject = (value: unknown): value is Record<string, unknown> =>
266
+ !!value && typeof value == 'object' && !Array.isArray(value)
267
+
268
+ const isFeedDocument = (value: unknown): value is FeedDocument =>
269
+ isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
270
+ && Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string')
271
+
272
+ const isControlled = (doc: FeedDocument) => doc._pups?.pupsControlled === true
273
+
274
+ const notControlled = (path: string) =>
275
+ 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).`)
276
+
277
+ const conflict = (what: string) => new PupsError('precondition_failed', `${what} changed in the meantime.`)
278
+
279
+ const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
280
+
281
+ const clone = <T>(value: T): T => structuredClone(value)
282
+
283
+ const serialize = (doc: FeedDocument) => JSON.stringify(doc, null, 2)
284
+
285
+ const byteLength = (text: string) => new TextEncoder().encode(text).length
286
+
287
+ const replaceAt = <T>(array: T[], index: number, value: T) => array.map((v, i) => i == index ? value : v)
288
+
289
+ /** Adds `incoming` items at the top of `existing`; an item whose id is already there replaces the old copy instead. */
290
+ function mergeItems(existing: FeedItem[], incoming: FeedItem[]): FeedItem[] {
291
+ const byId = new Map(incoming.map(item => [item.id, item]))
292
+ const present = new Set(existing.map(item => item.id))
293
+ return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)]
294
+ }
295
+
296
+ /** The index of an item (RFC-7 "Indexes"), or undefined if it has none. */
297
+ export function itemIndex(item: FeedItem): number | undefined {
298
+ const index = isObject(item._pups) ? item._pups.index : undefined
299
+ return typeof index == 'number' && Number.isSafeInteger(index) && index >= 0 ? index : undefined
300
+ }
301
+
302
+ const withIndex = (item: FeedItem, index: number): FeedItem => ({ ...item, _pups: { ...isObject(item._pups) ? item._pups : {}, index } })
303
+
304
+ /** The counter `_pups.next_index` of a file, if it has a valid one. */
305
+ function counterOf(doc: FeedDocument): number | undefined {
306
+ const next = doc._pups?.next_index
307
+ return typeof next == 'number' && Number.isSafeInteger(next) && next >= 0 ? next : undefined
308
+ }
309
+
310
+ /** The next free index: above every index of `items`, and at least each of `counters`. */
311
+ const nextFree = (items: FeedItem[], ...counters: (number | undefined)[]) =>
312
+ Math.max(0, ...counters.filter((c): c is number => c !== undefined), ...items.map(item => (itemIndex(item) ?? -1) + 1))
313
+
314
+ /**
315
+ * Gives the items without an index (newest first, as in a file) the next indexes from `next`, the oldest first
316
+ * (RFC-7 "Items without an index").
317
+ * @returns the items, and the counter after them.
318
+ */
319
+ function indexItems(items: FeedItem[], next: number): { items: FeedItem[]; next: number; changed: boolean } {
320
+ const result = [...items]
321
+ let changed = false
322
+ for (let i = result.length - 1; i >= 0; i--)
323
+ if (itemIndex(result[i]!) === undefined) {
324
+ result[i] = withIndex(result[i]!, next++)
325
+ changed = true
326
+ }
327
+ return { items: result, next, changed }
328
+ }
329
+
330
+ /** Every string inside `value`, deeply. */
331
+ function* strings(value: unknown): Generator<string> {
332
+ if (typeof value == 'string') yield value
333
+ else if (Array.isArray(value)) for (const v of value) yield* strings(v)
334
+ else if (isObject(value)) for (const v of Object.values(value)) yield* strings(v)
335
+ }
336
+
337
+ /** The file extension for a media type, preferring extensions that are served as exactly that type. */
338
+ function extensionForType(type: string): string | undefined {
339
+ const essence = type.split(';')[0]!.trim().toLowerCase()
340
+ const entries = Object.entries(fileTypes)
341
+ return entries.find(([, t]) => t.served == essence)?.[0] ?? entries.find(([, t]) => t.accepted.includes(essence))?.[0]
342
+ }
343
+
344
+ /**
345
+ * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json`, or a named feed
346
+ * `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
347
+ * The main feed keeps its media in `/feed/images/` and `/feed/media/`, since the rest of `/feed/` belongs to the
348
+ * named feeds.
349
+ *
350
+ * Get one from `session.feed()` or `session.feed('photos')`. The session needs the feed's scopes, see
351
+ * {@link feedScopes}. All writes are safe against concurrent changes by other apps and the owner: they are
352
+ * read-modify-write cycles with ETags, repeated when another client wrote in between.
353
+ */
354
+ export class PupsFeed {
355
+ /** The name of a named feed; undefined for the main feed. */
356
+ readonly name?: string
357
+ /** The feed file, e.g. `/feed.json` or `/feed/photos.json`. */
358
+ readonly path: string
359
+ /** The feed directory, e.g. `/feed/` or `/feed/photos/`. */
360
+ readonly directory: string
361
+ readonly #session: PupsSession
362
+ readonly #maxItems: number
363
+ readonly #archiveSize: number
364
+ readonly #archivesWanted: boolean
365
+ readonly #maxBytes?: number
366
+ readonly #maxAttempts: number
367
+
368
+ /** @internal Use `session.feed()`. */
369
+ constructor(session: PupsSession, name?: string, options: FeedOptions = {}) {
370
+ const { path, directory } = feedPaths(name)
371
+ this.name = name
372
+ this.path = path
373
+ this.directory = directory
374
+ this.#session = session
375
+ this.#maxItems = options.maxItems ?? 30
376
+ this.#archiveSize = options.archiveSize ?? 20
377
+ this.#archivesWanted = options.startArchives ?? true
378
+ this.#maxBytes = options.maxBytes
379
+ this.#maxAttempts = options.maxAttempts ?? 8
380
+ if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
381
+ throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.')
382
+ }
383
+
384
+ /** The public URL of the feed file, its `feed_url`. */
385
+ get url(): string {
386
+ return this.#session.publicUrl(this.path)
387
+ }
388
+
389
+ /** The scopes needed to write this feed. */
390
+ get scopes(): Scope[] {
391
+ return feedScopes(this.name)
392
+ }
393
+
394
+ /** Whether the session may write the feed file and the feed directory. */
395
+ get writable(): boolean {
396
+ return this.#session.canWrite(this.path) && this.#session.canWrite(this.#archivePath(0))
397
+ }
398
+
399
+ /** Reads the feed file and tells whether it exists, and whether PUPS clients may write it. */
400
+ async load(options: Signal = {}): Promise<FeedState> {
401
+ try {
402
+ const loaded = await this.#read(this.path, options.signal)
403
+ if (!loaded) return { status: 'missing' }
404
+ return isControlled(loaded.doc) ? { status: 'pups', feed: loaded.doc, etag: loaded.etag } : { status: 'foreign', feed: loaded.doc }
405
+ } catch (e) {
406
+ if (isPupsError(e, 'invalid_feed')) return { status: 'invalid' }
407
+ throw e
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the fixed fields
413
+ * and the `_pups` marker, and registers the feed in `host-meta.json` (unless `register` is false).
414
+ * @returns `registered`: false if the feed couldn't be registered; call `register()` again later, or tell the owner
415
+ * to add the link to `host-meta.json` by hand.
416
+ * @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`.
417
+ */
418
+ async create(setup: FeedSetup, options: Signal & { register?: boolean } = {}): Promise<{ url: string; registered: boolean }> {
419
+ const { icon, favicon, title, ...settings } = setup
420
+ if (typeof title != 'string' || !title.trim()) throw new PupsError('invalid_request', 'A feed needs a title.')
421
+ this.#checkSettings(settings)
422
+ this.#checkWritable()
423
+ const uploaded: MediaResult[] = []
424
+ try {
425
+ const iconFile = icon && await this.#upload(icon, 'images/icons/icon-', options.signal)
426
+ if (iconFile) uploaded.push(iconFile)
427
+ const faviconFile = favicon && await this.#upload(favicon, 'images/icons/favicon-', options.signal)
428
+ if (faviconFile) uploaded.push(faviconFile)
429
+ const { description, ...rest } = settings
430
+ const doc: FeedDocument = {
431
+ version: JSON_FEED_VERSION,
432
+ title,
433
+ home_page_url: this.#session.me,
434
+ feed_url: this.url,
435
+ ...description === undefined ? {} : { description },
436
+ user_comment: mainComment,
437
+ ...iconFile ? { icon: iconFile.url } : {},
438
+ ...faviconFile ? { favicon: faviconFile.url } : {},
439
+ ...rest,
440
+ items: [],
441
+ _pups: { about: PUPS_FEED_SPEC, pupsControlled: true },
442
+ }
443
+ await this.#session.create(this.path, serialize(doc), { contentType: FEED_CONTENT_TYPE, signal: options.signal })
444
+ } catch (e) {
445
+ await Promise.all(uploaded.map(file => this.#deleteQuietly(file.path)))
446
+ if (isPupsError(e, 'precondition_failed'))
447
+ throw new PupsError('precondition_failed', `${this.path} exists already. Use load() to see whether it can be used.`, { cause: e })
448
+ throw e
449
+ }
450
+ if (options.register === false) return { url: this.url, registered: false }
451
+ try {
452
+ return { url: this.url, registered: await this.register(options) }
453
+ } catch (e) {
454
+ // The feed exists now; a failed registration must not look like a failed setup.
455
+ if (isPupsError(e, 'aborted')) throw e
456
+ return { url: this.url, registered: false }
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Registers the feed in `host-meta.json` (RFC-7 "Registering feeds"), unless a link with the feed relation and
462
+ * this feed's URL exists already.
463
+ * @returns false if the server has no host-meta endpoint, or doesn't allow the feed relation for this path.
464
+ */
465
+ async register(options: Signal = {}): Promise<boolean> {
466
+ const hostMeta = this.#session.hostMeta
467
+ if (!hostMeta.available || !hostMeta.allowsRel(FEED_REL, this.path)) return false
468
+ const document = await hostMeta.get(options)
469
+ if (document.links?.some(link => link.rel == FEED_REL && link.href == this.url)) return true
470
+ await hostMeta.addLink({ rel: FEED_REL, href: this.path, type: FEED_CONTENT_TYPE }, options)
471
+ return true
472
+ }
473
+
474
+ /**
475
+ * Changes the owner's fields of the feed (RFC-7 "Editing a feed"): a value sets a field, `null` removes it.
476
+ * @returns the feed as written.
477
+ */
478
+ async updateSettings(changes: FeedSettingsChanges, options: Signal = {}): Promise<FeedDocument> {
479
+ this.#checkSettings(changes)
480
+ if (changes.title === null || (changes.title !== undefined && !changes.title.trim()))
481
+ throw new PupsError('invalid_request', 'A feed needs a title.')
482
+ return this.#transaction(async () => {
483
+ const main = await this.#readControlled(this.path, options.signal)
484
+ const doc = { ...main.doc }
485
+ for (const [key, value] of Object.entries(changes))
486
+ if (value === null) delete doc[key]
487
+ else if (value !== undefined) doc[key] = value
488
+ return this.#writeMain(doc, main.etag, options.signal)
489
+ })
490
+ }
491
+
492
+ /**
493
+ * Uploads a new icon (512 × 512) to `/feed/images/icons/` (`/feed/<name>/images/icons/` for a named feed) and
494
+ * deletes the old one, or removes it with `null`.
495
+ */
496
+ setIcon(media: MediaInput | null, options: Signal = {}): Promise<FeedDocument> {
497
+ return this.#setImage('icon', media, options.signal)
498
+ }
499
+
500
+ /** Uploads a new favicon (64 × 64) to the icons directory, like `setIcon()`, or removes it with `null`. */
501
+ setFavicon(media: MediaInput | null, options: Signal = {}): Promise<FeedDocument> {
502
+ return this.#setImage('favicon', media, options.signal)
503
+ }
504
+
505
+ /**
506
+ * Uploads an image, audio or video file into the feed directory under a new, unique name, by default
507
+ * `images/<year>/…` for images and `media/<year>/…` for everything else. Reference it from a post by its `url`.
508
+ * For the main feed, `folder` must be inside `images/` or `media/`: the rest of `/feed/` belongs to named feeds.
509
+ */
510
+ async uploadMedia(media: MediaInput, options: Signal & { folder?: string } = {}): Promise<MediaResult> {
511
+ const { type } = this.#mediaType(media)
512
+ const folder = (options.folder ?? (type.startsWith('image/') ? 'images' : 'media')).replace(/^\/+|\/+$/g, '')
513
+ if (folder == 'images/icons' || folder.startsWith('images/icons/'))
514
+ throw new PupsError('invalid_request', `${this.directory}images/icons/ is reserved for the feed's icons (RFC-7, Icons).`)
515
+ if (this.name === undefined && !mainMediaFolders.includes(folder.split('/')[0]!))
516
+ 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).`)
517
+ return this.#upload(media, `${folder}/${new Date().getUTCFullYear()}/`, options.signal)
518
+ }
519
+
520
+ /**
521
+ * Adds a post (RFC-7 "Posting with archives"): first to the newest archive, or to a new archive once the newest
522
+ * holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
523
+ * archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
524
+ * media with `uploadMedia()` before posting.
525
+ * @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
526
+ * archives, the feed file's URL plus `#<id>`, valid while the post is among the newest.
527
+ */
528
+ async addPost(input: PostInput, options: Signal = {}): Promise<PostResult> {
529
+ const item = this.#newItem(input)
530
+ const signal = options.signal
531
+ let archiveUrl = ''
532
+ let stored = item
533
+ let firstAttempt = true
534
+ await this.#transaction(async () => {
535
+ const main = await this.#readControlled(this.path, signal)
536
+ // On a retry, the item may be in the feed file already: another client repaired it from the archive.
537
+ if (firstAttempt && main.doc.items.some(i => i.id == item.id))
538
+ throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`)
539
+ firstAttempt = false
540
+ const doc: FeedDocument = { ...main.doc, _pups: { ...main.doc._pups } }
541
+ const hasArchives = this.#archiveNumber(doc._pups!.archive_url) !== undefined
542
+ if (!hasArchives && !this.#archivesWanted) {
543
+ // A feed without archives: the feed file is all there is, and holds the counter (RFC-7 "Posting").
544
+ archiveUrl = this.url
545
+ const indexed = indexItems(doc.items, nextFree(doc.items, counterOf(doc)))
546
+ stored = withIndex(item, indexed.next)
547
+ doc._pups!.next_index = indexed.next + 1
548
+ await this.#writeMain({ ...doc, items: this.#newestItems([stored], indexed.items, doc) }, main.etag, signal)
549
+ return
550
+ }
551
+ if (!hasArchives) {
552
+ const started = await this.#startArchives(main, signal)
553
+ if (started) {
554
+ doc._pups!.archive_url = started.url
555
+ doc.items = started.items
556
+ }
557
+ }
558
+ const added = await this.#addToArchive(main, doc, item, signal)
559
+ archiveUrl = added.url
560
+ stored = added.item
561
+ doc._pups!.archive_url = added.url
562
+ if (!hasArchives) {
563
+ // The old chain of a handed-over feed now continues behind the oldest archive, and the newest archive
564
+ // holds the counter.
565
+ delete doc.next_url
566
+ delete doc._pups!.next_index
567
+ }
568
+ doc.items = this.#newestItems(added.recent, doc.items, doc)
569
+ await this.#writeMain(doc, main.etag, signal)
570
+ })
571
+ return this.#result(stored, archiveUrl)
572
+ }
573
+
574
+ /**
575
+ * Gives every item of the feed without an index one (RFC-7 "Indexing an existing feed"), and sets the counter.
576
+ * `addPost()` does this by itself before the first post to a feed that hasn't been indexed yet; call it to
577
+ * index a feed without posting.
578
+ */
579
+ async assignIndexes(options: Signal = {}): Promise<void> {
580
+ const signal = options.signal
581
+ await this.#transaction(async () => {
582
+ const main = await this.#readControlled(this.path, signal)
583
+ const newest = this.#archiveNumber(main.doc._pups?.archive_url)
584
+ if (newest === undefined) {
585
+ const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
586
+ if (indexed.changed || counterOf(main.doc) !== indexed.next)
587
+ await this.#writeMain({ ...main.doc, items: indexed.items, _pups: { ...main.doc._pups, next_index: indexed.next } }, main.etag, signal)
588
+ return
589
+ }
590
+ const archive = await this.#readArchive(this.#archivePath(newest), signal)
591
+ if (archive && archive != 'foreign' && (counterOf(archive.doc) === undefined || archive.doc.items.some(item => itemIndex(item) === undefined)))
592
+ await this.#indexArchives(main, signal)
593
+ })
594
+ }
595
+
596
+ /**
597
+ * Finds a post by id in the archives (or, for a handed-over feed without archives yet, in the feed file).
598
+ * @returns undefined if there is no such post.
599
+ */
600
+ async getPost(id: string, options: Signal = {}): Promise<PostResult | undefined> {
601
+ const main = await this.#read(this.path, options.signal)
602
+ const found = main && await this.#find(main, id, options.signal)
603
+ return found && this.#result(found.file.doc.items[found.index]!, this.#session.publicUrl(found.file.path))
604
+ }
605
+
606
+ /**
607
+ * All posts, newest first: the archives from `_pups.archive_url` along `next_url` (for a feed without archives,
608
+ * the feed file and its `next_url` chain). Each post is returned once.
609
+ */
610
+ async *posts(options: Signal = {}): AsyncGenerator<FeedItem> {
611
+ const main = await this.#read(this.path, options.signal)
612
+ if (!main) return
613
+ const seen = new Set<string>()
614
+ for await (const file of this.#chain(main, options.signal))
615
+ for (const item of file.doc.items)
616
+ if (!seen.has(item.id)) {
617
+ seen.add(item.id)
618
+ yield item
619
+ }
620
+ }
621
+
622
+ /**
623
+ * Edits a post in its archive, and in the feed file if it is among the newest items (RFC-7 "Editing and deleting
624
+ * items"), and sets `date_modified`. `changes` is either an object (a value sets a field, `null` removes it), or
625
+ * a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
626
+ * function may run more than once.
627
+ *
628
+ * Apps should edit posts only when the owner asks them to, whichever app created them.
629
+ * @throws {PupsError} `not_found`
630
+ */
631
+ async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: Signal = {}): Promise<PostResult> {
632
+ const signal = options.signal
633
+ return this.#transaction(async () => {
634
+ const { main, file, index } = await this.#findWritable(id, signal)
635
+ const old = file.doc.items[index]!
636
+ const fileUrl = this.#session.publicUrl(file.path)
637
+ const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes)
638
+ if (!changed) return this.#result(old, fileUrl)
639
+ const oldIndex = itemIndex(old)
640
+ let item: FeedItem = { ...changed, id, date_modified: now() }
641
+ // The index never changes (RFC-7 "Indexes").
642
+ if (oldIndex !== undefined) item = withIndex(item, oldIndex)
643
+ if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
644
+ const mainIndex = main.doc.items.findIndex(i => i.id == id)
645
+ if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
646
+ return this.#result(item, fileUrl)
647
+ })
648
+ }
649
+
650
+ /**
651
+ * Deletes a post from its archive and from the feed file, which is then filled up again with the newest items
652
+ * from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the post references
653
+ * and no other post does; this reads all archives.
654
+ * @returns the deleted item, and the public URLs of the deleted media files.
655
+ * @throws {PupsError} `not_found`
656
+ */
657
+ async deletePost(id: string, options: Signal & { deleteMedia?: boolean } = {}): Promise<{ item: FeedItem; deletedMedia: string[] }> {
658
+ const signal = options.signal
659
+ const item = await this.#transaction(async () => {
660
+ const { main, file, index } = await this.#findWritable(id, signal)
661
+ const item = file.doc.items[index]!
662
+ if (file != main) {
663
+ await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal)
664
+ // Fill the feed file up again from the archives, which no longer contain the item.
665
+ const newest: FeedItem[] = []
666
+ for await (const archive of this.#chain(main, signal)) {
667
+ newest.push(...archive.doc.items.filter(i => i.id != id))
668
+ if (newest.length >= this.#maxItems) break
669
+ }
670
+ await this.#writeMain({ ...main.doc, items: this.#newestItems(newest, [], main.doc) }, main.etag, signal)
671
+ } else
672
+ await this.#writeMain({ ...main.doc, items: main.doc.items.filter(i => i.id != id) }, main.etag, signal)
673
+ return item
674
+ })
675
+ const deletedMedia: string[] = []
676
+ if (options.deleteMedia) {
677
+ const candidates = new Set(this.#mediaUrls(item))
678
+ if (candidates.size)
679
+ for await (const other of this.posts(options))
680
+ for (const url of this.#mediaUrls(other)) candidates.delete(url)
681
+ for (const url of candidates) {
682
+ const path = pathFromPublicUrl(this.#session.server, url)
683
+ if (path && await this.#deleteQuietly(path, signal)) deletedMedia.push(url)
684
+ }
685
+ }
686
+ return { item, deletedMedia }
687
+ }
688
+
689
+ // Reading
690
+
691
+ /**
692
+ * Reads a feed file or archive from `storage_base`.
693
+ * @returns undefined if it doesn't exist.
694
+ * @throws {PupsError} `invalid_feed` if it is not a JSON Feed.
695
+ */
696
+ async #read(path: string, signal?: AbortSignal): Promise<Loaded | undefined> {
697
+ const file = await this.#session.get(path, { signal })
698
+ if (!file) return
699
+ if (!file.etag)
700
+ throw new PupsError('server_error', `The server sends no ETag for ${path}, so it can't be changed safely. It must expose the ETag header to browsers (RFC-6, CORS).`)
701
+ let doc: unknown
702
+ try {
703
+ doc = await file.json()
704
+ } catch {
705
+ // Not JSON: handled below.
706
+ }
707
+ if (!isFeedDocument(doc)) throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`)
708
+ return { path, doc, etag: file.etag }
709
+ }
710
+
711
+ /** Reads a file that must exist and carry the `_pups` marker. */
712
+ async #readControlled(path: string, signal?: AbortSignal): Promise<Loaded> {
713
+ const loaded = await this.#read(path, signal)
714
+ if (!loaded)
715
+ throw new PupsError('not_found', path == this.path ? `There is no feed at ${path} yet. Set it up with create().` : `${path} doesn't exist.`)
716
+ if (!isControlled(loaded.doc)) throw notControlled(path)
717
+ return loaded
718
+ }
719
+
720
+ /**
721
+ * The files that hold all items: the archives from `_pups.archive_url` along `next_url`, as far as they are files
722
+ * on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
723
+ * the pages its `next_url` names.
724
+ */
725
+ async *#chain(main: Loaded, signal?: AbortSignal): AsyncGenerator<Loaded> {
726
+ const visited = new Set<string>([main.path])
727
+ const archive = main.doc._pups?.archive_url
728
+ let file: Loaded | undefined = main
729
+ let next = archive && this.#archiveNumber(archive) !== undefined ? archive : undefined
730
+ if (next) file = undefined
731
+ else yield main
732
+ for (;;) {
733
+ if (file) next = file.doc.next_url
734
+ const path = next && pathFromPublicUrl(this.#session.server, next)
735
+ if (!path || visited.has(path)) return
736
+ visited.add(path)
737
+ try {
738
+ file = await this.#read(path, signal)
739
+ } catch (e) {
740
+ if (!isPupsError(e, 'invalid_feed', 'invalid_path')) throw e
741
+ return
742
+ }
743
+ if (!file) return
744
+ yield file
745
+ }
746
+ }
747
+
748
+ async #find(main: Loaded, id: string, signal?: AbortSignal): Promise<Found | undefined> {
749
+ for await (const file of this.#chain(main, signal)) {
750
+ const index = file.doc.items.findIndex(item => item.id == id)
751
+ if (index >= 0) return { main, file, index }
752
+ }
753
+ return
754
+ }
755
+
756
+ async #findWritable(id: string, signal?: AbortSignal): Promise<Found> {
757
+ const main = await this.#readControlled(this.path, signal)
758
+ const found = await this.#find(main, id, signal)
759
+ if (!found) throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`)
760
+ if (!isControlled(found.file.doc)) throw notControlled(found.file.path)
761
+ return found
762
+ }
763
+
764
+ // Writing
765
+
766
+ /** Runs `operation` again when another client changed a file in between, up to `maxAttempts` times. */
767
+ async #transaction<T>(operation: () => Promise<T>): Promise<T> {
768
+ for (let attempt = 1; ; attempt++)
769
+ try {
770
+ return await operation()
771
+ } catch (e) {
772
+ if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts) throw e
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
778
+ * and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). The optional `next_url` of a feed with
779
+ * archives is kept equal to `archive_url` (RFC-7 "Reading").
780
+ */
781
+ async #writeMain(doc: FeedDocument, etag: string, signal?: AbortSignal): Promise<FeedDocument> {
782
+ const { author, ...rest } = doc
783
+ const fixed: FeedDocument = {
784
+ ...rest,
785
+ version: JSON_FEED_VERSION,
786
+ home_page_url: this.#session.me,
787
+ feed_url: this.url,
788
+ user_comment: mainComment,
789
+ }
790
+ if (author !== undefined && fixed.authors === undefined) fixed.authors = [author as FeedAuthor]
791
+ if (fixed.next_url !== undefined && this.#archiveNumber(fixed._pups?.archive_url) !== undefined) fixed.next_url = fixed._pups!.archive_url
792
+ await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal })
793
+ return fixed
794
+ }
795
+
796
+ /** Writes an archive with `items`, and with the counter `next_index` if given. */
797
+ async #writeArchive(archive: Loaded, items: FeedItem[], signal?: AbortSignal, nextIndex?: number) {
798
+ const doc = nextIndex === undefined ? { ...archive.doc, items } : { ...archive.doc, items, _pups: { ...archive.doc._pups, next_index: nextIndex } }
799
+ await this.#session.replace(archive.path, serialize(doc), archive.etag, { contentType: FEED_CONTENT_TYPE, signal })
800
+ }
801
+
802
+ /**
803
+ * The items of the feed file: the newest archive items first (which also repairs items an interrupted post wrote
804
+ * only into the archive), then the other items of the feed file, at most `maxItems`, fewer if `maxBytes` is set
805
+ * and exceeded, but at least 10.
806
+ */
807
+ #newestItems(recent: FeedItem[], current: FeedItem[], doc: FeedDocument): FeedItem[] {
808
+ const ids = new Set(recent.map(item => item.id))
809
+ const items = [...recent, ...current.filter(item => !ids.has(item.id))].slice(0, this.#maxItems)
810
+ if (this.#maxBytes)
811
+ while (items.length > minFeedItems && byteLength(serialize({ ...doc, items })) > this.#maxBytes) items.pop()
812
+ return items
813
+ }
814
+
815
+ // Archives
816
+
817
+ #archivePath(n: number) {
818
+ return `${this.directory}feed.${String(n).padStart(6, '0')}.json`
819
+ }
820
+
821
+ #archiveUrl(n: number) {
822
+ return this.#session.publicUrl(this.#archivePath(n))
823
+ }
824
+
825
+ /** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
826
+ #archiveNumber(url: string | undefined): number | undefined {
827
+ const path = url && pathFromPublicUrl(this.#session.server, url)
828
+ if (!path?.startsWith(this.directory)) return
829
+ const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length))
830
+ return match ? Number(match[1]) : undefined
831
+ }
832
+
833
+ /** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
834
+ #newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, nextIndex?: number): FeedDocument {
835
+ const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main
836
+ const { archive_url: _archive, next_index: _counter, ...marker } = _pups ?? {}
837
+ const podcast = fields._podcast
838
+ if (isObject(podcast) && 'liveItems' in podcast) {
839
+ const { liveItems: _live, ...rest } = podcast
840
+ fields._podcast = rest
841
+ }
842
+ return {
843
+ ...fields,
844
+ version: JSON_FEED_VERSION,
845
+ home_page_url: this.#session.me,
846
+ feed_url: this.#archiveUrl(n),
847
+ user_comment: archiveComment(this.url),
848
+ ...nextUrl ? { next_url: nextUrl } : {},
849
+ items,
850
+ _pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url, ...nextIndex === undefined ? {} : { next_index: nextIndex } },
851
+ }
852
+ }
853
+
854
+ async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal, nextIndex?: number) {
855
+ await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl, nextIndex)), { contentType: FEED_CONTENT_TYPE, signal })
856
+ }
857
+
858
+ /**
859
+ * Reads an archive for writing.
860
+ * @returns undefined if it doesn't exist, 'foreign' if it exists but is no PUPS archive.
861
+ */
862
+ async #readArchive(path: string, signal?: AbortSignal): Promise<Loaded | 'foreign' | undefined> {
863
+ try {
864
+ const loaded = await this.#read(path, signal)
865
+ return loaded && !isControlled(loaded.doc) ? 'foreign' : loaded
866
+ } catch (e) {
867
+ if (isPupsError(e, 'invalid_feed')) return 'foreign'
868
+ throw e
869
+ }
870
+ }
871
+
872
+ /**
873
+ * Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
874
+ * archives"). The items get indexes first, and the newest archive the counter. The oldest archive continues the
875
+ * feed's `next_url` chain.
876
+ * @returns the URL of the newest archive and the feed's items with their indexes, or undefined if the feed has no
877
+ * items.
878
+ */
879
+ async #startArchives(main: Loaded, signal?: AbortSignal): Promise<{ url: string; items: FeedItem[] } | undefined> {
880
+ const indexed = indexItems(main.doc.items, nextFree(main.doc.items, counterOf(main.doc)))
881
+ const oldestFirst = [...indexed.items].reverse()
882
+ const count = Math.ceil(oldestFirst.length / this.#archiveSize)
883
+ let url: string | undefined
884
+ for (let n = 0; n < count; n++) {
885
+ const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse()
886
+ const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url
887
+ const nextIndex = n == count - 1 ? indexed.next : undefined
888
+ try {
889
+ await this.#createArchive(n, main.doc, items, nextUrl, signal, nextIndex)
890
+ } catch (e) {
891
+ if (!isPupsError(e, 'precondition_failed')) throw e
892
+ // Left behind by an interrupted start: complete it, as long as it holds only these items.
893
+ const existing = await this.#readArchive(this.#archivePath(n), signal)
894
+ const ids = new Set(items.map(item => item.id))
895
+ if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
896
+ 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).`)
897
+ await this.#writeArchive(existing, items, signal, nextIndex)
898
+ }
899
+ url = this.#archiveUrl(n)
900
+ }
901
+ return url ? { url, items: indexed.items } : undefined
902
+ }
903
+
904
+ /**
905
+ * Indexes a feed with archives whose newest archive has no counter, or items without an index (RFC-7 "Indexing an
906
+ * existing feed"): gives every archived item without an index one, the oldest first, writes the changed archives
907
+ * from the oldest to the newest, the newest with the counter, and then the feed file's copies.
908
+ */
909
+ async #indexArchives(main: Loaded, signal?: AbortSignal): Promise<void> {
910
+ const files: Loaded[] = []
911
+ for await (const file of this.#chain(main, signal)) {
912
+ // Pages behind the oldest archive of a handed-over feed are never written, and keep their items unindexed.
913
+ if (file == main || !isControlled(file.doc)) break
914
+ files.push(file)
915
+ }
916
+ if (!files.length) return
917
+ let next = nextFree(files.flatMap(file => file.doc.items), ...files.map(file => counterOf(file.doc)))
918
+ const indexes = new Map<string, number>()
919
+ for (const file of [...files].reverse()) {
920
+ const indexed = indexItems(file.doc.items, next)
921
+ next = indexed.next
922
+ for (const item of indexed.items) indexes.set(item.id, itemIndex(item)!)
923
+ const newest = file == files[0]
924
+ if (indexed.changed || (newest && counterOf(file.doc) !== next)) await this.#writeArchive(file, indexed.items, signal, newest ? next : undefined)
925
+ }
926
+ let changed = false
927
+ const items = main.doc.items.map(item => {
928
+ const index = indexes.get(item.id)
929
+ if (index === undefined || itemIndex(item) === index) return item
930
+ changed = true
931
+ return withIndex(item, index)
932
+ })
933
+ if (changed) await this.#writeMain({ ...main.doc, items }, main.etag, signal)
934
+ }
935
+
936
+ /**
937
+ * Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
938
+ * "Posting"). Writes only archives; the caller writes the feed file afterwards.
939
+ * The item gets its index from the archive's counter (RFC-7 "Indexes"); a newest archive without a counter is
940
+ * indexed first, and the post then starts again.
941
+ * @returns the archive's URL, the newest items known from the archives, newest first, and the item as stored.
942
+ */
943
+ async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal): Promise<{ url: string; recent: FeedItem[]; item: FeedItem }> {
944
+ const newest = this.#archiveNumber(doc._pups?.archive_url)
945
+ let previous: FeedItem[] = []
946
+ // The index for the item if it goes into a new archive.
947
+ let next = nextFree(doc.items, newest === undefined ? counterOf(doc) : undefined)
948
+ if (newest !== undefined) {
949
+ const existing = await this.#readArchive(this.#archivePath(newest), signal)
950
+ if (!existing) {
951
+ // The owner deleted it: create it again, linked to the next older archive, with an index above all known ones.
952
+ const before = newest ? await this.#readArchive(this.#archivePath(newest - 1), signal) : undefined
953
+ if (before && before != 'foreign') next = nextFree([...doc.items, ...before.doc.items], counterOf(before.doc))
954
+ const stored = withIndex(item, next)
955
+ await this.#createArchive(newest, doc, [stored], newest ? this.#archiveUrl(newest - 1) : undefined, signal, next + 1)
956
+ return { url: this.#archiveUrl(newest), recent: [stored], item: stored }
957
+ }
958
+ if (existing != 'foreign') {
959
+ if (counterOf(existing.doc) === undefined) {
960
+ await this.#indexArchives(main, signal)
961
+ throw conflict(`${this.path} was indexed, so it`)
962
+ }
963
+ // Items that a client without indexes added get theirs first (RFC-7 "Items without an index").
964
+ const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc)))
965
+ const copy = indexed.items.find(i => i.id == item.id)
966
+ const stored = withIndex(item, copy ? itemIndex(copy)! : indexed.next)
967
+ const merged = mergeItems(indexed.items, [stored])
968
+ if (merged.length <= this.#archiveSize) {
969
+ await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
970
+ return { url: this.#archiveUrl(newest), recent: merged, item: stored }
971
+ }
972
+ if (indexed.changed) await this.#writeArchive(existing, indexed.items, signal, indexed.next)
973
+ previous = indexed.items
974
+ next = indexed.next
975
+ }
976
+ }
977
+ // The archive before the new one: the newest, or for a feed without archives the end of its old chain.
978
+ const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest)
979
+ for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
980
+ const stored = withIndex(item, next)
981
+ try {
982
+ await this.#createArchive(n, doc, [stored], nextUrl, signal, next + 1)
983
+ return { url: this.#archiveUrl(n), recent: [stored, ...previous], item: stored }
984
+ } catch (e) {
985
+ if (!isPupsError(e, 'precondition_failed')) throw e
986
+ }
987
+ // The archive exists: left behind by an interrupted client, or created by another client just now.
988
+ const existing = await this.#readArchive(this.#archivePath(n), signal)
989
+ if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
990
+ const indexed = indexItems(existing.doc.items, nextFree(existing.doc.items, counterOf(existing.doc), next))
991
+ const copy = indexed.items.find(i => i.id == item.id)
992
+ const added = withIndex(item, copy ? itemIndex(copy)! : indexed.next)
993
+ const merged = mergeItems(indexed.items, [added])
994
+ if (merged.length <= this.#archiveSize) {
995
+ await this.#writeArchive(existing, merged, signal, copy ? indexed.next : indexed.next + 1)
996
+ return { url: this.#archiveUrl(n), recent: [...merged, ...previous], item: added }
997
+ }
998
+ }
999
+ const current = await this.#session.get(this.path, { signal })
1000
+ if (current?.etag != main.etag) throw conflict(this.path)
1001
+ }
1002
+ throw new PupsError('conflict', `No free archive number in ${this.directory}.`)
1003
+ }
1004
+
1005
+ // Items and media
1006
+
1007
+ #newItem(input: PostInput): FeedItem {
1008
+ const { id, markdown, date_published, ...fields } = input
1009
+ if (id !== undefined && (typeof id != 'string' || !id))
1010
+ throw new PupsError('invalid_request', 'A post id must be a non-empty string.')
1011
+ const item: FeedItem = {
1012
+ id: id ?? randomString(12),
1013
+ ...fields,
1014
+ date_published: date_published instanceof Date ? date_published.toISOString() : date_published ?? now(),
1015
+ }
1016
+ if (markdown !== undefined) this.#setMarkdown(item, markdown)
1017
+ if (item.content_html === undefined && item.content_text === undefined)
1018
+ throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).')
1019
+ // The index is given out when the item is added (RFC-7 "Indexes").
1020
+ if (isObject(item._pups)) {
1021
+ const { index: _index, ...marker } = item._pups
1022
+ if (Object.keys(marker).length) item._pups = marker
1023
+ else delete item._pups
1024
+ }
1025
+ return item
1026
+ }
1027
+
1028
+ #applyChanges(item: FeedItem, changes: PostChanges): FeedItem {
1029
+ for (const [key, value] of Object.entries(changes)) {
1030
+ if (key == 'id') throw new PupsError('invalid_request', 'The id of a post can\'t be changed.')
1031
+ if (value === undefined) continue
1032
+ if (key == 'markdown') {
1033
+ if (value === null) {
1034
+ const source = isObject(item._source) ? { ...item._source } : undefined
1035
+ if (source) {
1036
+ delete source.markdown
1037
+ item._source = source
1038
+ }
1039
+ } else this.#setMarkdown(item, value as string)
1040
+ } else if (value === null) delete item[key]
1041
+ else item[key] = value instanceof Date ? value.toISOString() : value
1042
+ }
1043
+ if (item.content_html === undefined && item.content_text === undefined)
1044
+ throw new PupsError('invalid_request', 'A post needs content_html or content_text (JSON Feed requires content).')
1045
+ return item
1046
+ }
1047
+
1048
+ /** Stores Markdown in `_source.markdown` (RFC-1), with `content_text` as the fallback JSON Feed requires. */
1049
+ #setMarkdown(item: FeedItem, markdown: string) {
1050
+ const source = isObject(item._source) ? item._source : {}
1051
+ item._source = { about: RFC1_URL, ...source, markdown }
1052
+ if (item.content_html === undefined) item.content_text = markdown
1053
+ }
1054
+
1055
+ #result(item: FeedItem, fileUrl: string): PostResult {
1056
+ const index = itemIndex(item)
1057
+ return { id: item.id, ...index === undefined ? {} : { index }, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` }
1058
+ }
1059
+
1060
+ /**
1061
+ * The URLs of this feed's media files (not icons, not archives) that an item references. For the main feed, only
1062
+ * `/feed/images/` and `/feed/media/`, so that files of named feeds are never taken for its own.
1063
+ */
1064
+ #mediaUrls(item: FeedItem): string[] {
1065
+ const base = this.#session.publicUrl(this.directory)
1066
+ const bases = this.name === undefined ? mainMediaFolders.map(folder => `${base}${folder}/`) : [base]
1067
+ const icons = `${base}images/icons/`
1068
+ const urls = new Set<string>()
1069
+ for (const text of strings(item))
1070
+ for (const [url] of text.matchAll(/https?:\/\/[^\s"'<>()]+/g))
1071
+ if (bases.some(b => url.startsWith(b)) && !url.startsWith(icons) && this.#archiveNumber(url) === undefined) urls.add(url)
1072
+ return [...urls]
1073
+ }
1074
+
1075
+ #mediaType(media: MediaInput): { type: string; extension: string; body: Body } {
1076
+ const blob = typeof Blob != 'undefined' && media instanceof Blob ? media : undefined
1077
+ const given = blob ? undefined : media as { body: Body; type?: string; extension?: string }
1078
+ const nameExtension = (blob as File | undefined)?.name?.match(/\.([a-z0-9]+)$/i)?.[1]
1079
+ const type = blob?.type || given?.type
1080
+ const extension = (given?.extension ?? nameExtension ?? (type ? extensionForType(type) : undefined))?.toLowerCase().replace(/^\./, '')
1081
+ const fileType = extension ? fileTypes[extension] : undefined
1082
+ if (!extension || !fileType)
1083
+ throw new PupsError('unsupported_type', `Can't tell the file type of the upload${extension ? ` (".${extension}" is not allowed)` : ''}. Pass a Blob with a type, or { body, type } or { body, extension } (RFC-6, File types).`)
1084
+ return { type: fileType.served, extension, body: blob ?? given!.body }
1085
+ }
1086
+
1087
+ async #upload(media: MediaInput, prefix: string, signal?: AbortSignal): Promise<MediaResult> {
1088
+ const { type, extension, body } = this.#mediaType(media)
1089
+ const path = `${this.directory}${prefix}${randomString(9)}.${extension}`
1090
+ const result = await this.#session.create(path, body, { signal })
1091
+ const size = typeof body == 'string' ? byteLength(body) : body instanceof Blob ? body.size : (body as ArrayBuffer | ArrayBufferView).byteLength
1092
+ // Feed directories are public, so the result always has a URL.
1093
+ return { path, url: result.url!, type, size }
1094
+ }
1095
+
1096
+ async #setImage(field: 'icon' | 'favicon', media: MediaInput | null, signal?: AbortSignal): Promise<FeedDocument> {
1097
+ const uploaded = media ? await this.#upload(media, `images/icons/${field}-`, signal) : undefined
1098
+ let old: unknown
1099
+ let doc: FeedDocument
1100
+ try {
1101
+ doc = await this.#transaction(async () => {
1102
+ const main = await this.#readControlled(this.path, signal)
1103
+ old = main.doc[field]
1104
+ const changed = { ...main.doc }
1105
+ if (uploaded) changed[field] = uploaded.url
1106
+ else delete changed[field]
1107
+ return this.#writeMain(changed, main.etag, signal)
1108
+ })
1109
+ } catch (e) {
1110
+ if (uploaded) await this.#deleteQuietly(uploaded.path)
1111
+ throw e
1112
+ }
1113
+ const oldPath = typeof old == 'string' && old != uploaded?.url ? pathFromPublicUrl(this.#session.server, old) : undefined
1114
+ if (oldPath?.startsWith(`${this.directory}images/icons/`)) await this.#deleteQuietly(oldPath, signal)
1115
+ return doc
1116
+ }
1117
+
1118
+ /** Deletes a file, ignoring a missing one. @returns whether it was deleted. */
1119
+ async #deleteQuietly(path: string, signal?: AbortSignal): Promise<boolean> {
1120
+ try {
1121
+ await this.#session.delete(path, { signal })
1122
+ return true
1123
+ } catch (e) {
1124
+ if (isPupsError(e, 'not_found')) return false
1125
+ throw e
1126
+ }
1127
+ }
1128
+
1129
+ #checkSettings(settings: Record<string, unknown>) {
1130
+ for (const key of Object.keys(settings))
1131
+ if (reservedFields.has(key))
1132
+ throw new PupsError('invalid_request', key == 'icon' || key == 'favicon'
1133
+ ? `Set ${key} with ${key == 'icon' ? 'setIcon' : 'setFavicon'}(), which stores it in images/icons/ (RFC-7, Icons).`
1134
+ : `"${key}" is fixed or managed by RFC-7 and can't be set.`)
1135
+ else if (!['title', 'description', 'authors', 'language', 'expired'].includes(key) && !key.startsWith('_'))
1136
+ 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 "_".`)
1137
+ }
1138
+
1139
+ #checkWritable() {
1140
+ if (!this.writable)
1141
+ throw new PupsError('insufficient_scope', `Writing ${this.path} needs the scopes ${this.scopes.join(' ')} (RFC-7, Server requirements).`)
1142
+ }
1143
+ }
1144
+
1145
+ /** The feeds registered in the owner's `host-meta.json` (RFC-7 "Registering feeds"). */
1146
+ export async function listFeeds(session: PupsSession, options: Signal & FeedOptions = {}): Promise<FeedLink[]> {
1147
+ const document = await session.hostMeta.get(options)
1148
+ const links = (document.links ?? []).filter(link => link.rel == FEED_REL && typeof link.href == 'string')
1149
+ return links.map(link => {
1150
+ const url = link.href!
1151
+ const path = pathFromPublicUrl(session.server, url)
1152
+ const name = path == '/feed.json' ? null : /^\/feed\/([^/]+)\.json$/.exec(path ?? '')?.[1]
1153
+ let feed: PupsFeed | undefined
1154
+ if (name !== undefined)
1155
+ try {
1156
+ feed = new PupsFeed(session, name ?? undefined, options)
1157
+ } catch {
1158
+ // Not a valid feed name, e.g. an archive or a link the owner added.
1159
+ }
1160
+ return { url, ...typeof link.type == 'string' ? { type: link.type } : {}, ...feed ? { feed } : {} }
1161
+ })
1162
+ }